我正在使用 CakePHP 2.5.3.0 开发一个应用程序,然后我偶然发现了 AJAX 的一个问题:
我使用从 jQuery 到 CakePHP 的 AJAX 请求来发送用户的登录名和密码,然后 CakePHP 应该返回经过验证的 JSON 响应。问题是:每当我在控制器的操作方法中使用模型方法时,JSON 响应都会在 JSON 开始之前出现意外的字符。
这是在 Google Chrome 上看到响应时的屏幕截图:https://i.stack.imgur.com/bKx3i.png https://i.stack.imgur.com/bKx3i.png
jQuery AJAX 请求代码在这里:
$.ajax({
url: "/login/signin.json",
cache: false,
type: "POST",
dataType: "json",
data: {
email: $("#login-form").find("input[name=email]").val(),
password: $("#login-form").find("input[name=password]").val()
},
success: function(response) {
self.callback.login(response);
}
});
这是 LoginController 的“登录”方法:
public function signin() {
if(!$this->request->is("ajax"))
throw new BadRequestException();
$this->layout = 'ajax';
$this->response->disableCache();
$this->RequestHandler->respondAs("application/json");
if($this->request->is("post")):
$account = $this->Account->validateAccount($this->request->data['email'], Security::hash($this->request->data['password'],"sha1",true));
if(count($account)>0):
$account = $account['Account'];
$message = array( "success" => true,
"message" => "[]");
$AccountManager = new AccountSessionManager();
$AccountManager->setId($account['id_account']);
else:
$message = array( "error" => true,
"message" => "The entered e-mail or password are invalid",
"code" => 2 );
endif;
else:
$message = array( "error" => true,
"message" => "No POST request.",
"code" => 1 );
endif;
$this->set("message", $message);
$this->set("_serialize", array('message'));
$this->render("ajax");
}
我上面渲染的“ajax”视图文件是一个简单的
<?php echo $message ?>
但每当我改变这条线
$account = $this->Account->validateAccount($this->request->data['email'], Security::hash($this->request->data['password'],"sha1",true));
to
$account = array();
在 json 响应之前我没有得到那个奇怪的字符。
我不知道为什么会发生这种情况,但这种情况发生了only当我使用any控制器中的模型方法...
顺便说一句,我从 javascript 得到的错误是:
未捕获的语法错误:意外的标记
而我所说的意想不到的字符就是Chrome中json前面的小红点。