【发布时间】:2014-08-31 00:59:44
【问题描述】:
我正在使用 CakePHP 2.5.3.0 开发一个应用程序,然后我偶然发现了 AJAX 的一个问题:
我正在使用从 jQuery 到 CakePHP 的 AJAX 请求来发送用户的登录名和密码,然后 CakePHP 应该返回一个经过验证的 JSON 响应。问题是:每当我在 Controller 中的操作方法中使用 Model 方法时,JSON 响应在 JSON 开始之前出现一个意外字符。
这是在 Google Chrome 上看到响应时的屏幕截图: http://i.imgur.com/m5x6X4G.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));
到
$account = array();
在 json 响应之前我没有得到那个奇怪的字符。
我不知道为什么会发生这种情况,但是只有当我在控制器中使用 any 模型方法时才会发生这种情况...
顺便说一句,我从 javascript 得到的错误是:
Uncaught SyntaxError: Unexpected token
我所说的意外字符是 json 之前 Chrome 中的小红点。
【问题讨论】:
标签: php jquery ajax json cakephp