我用$.post希望实现异步提交的功能,代码如下:
$.post(addURL,
{pid : id},
function (data) {
alert("回调函数");
alert(data["status"]);
},
"json")
.success(function () {alert("success");})
.error(function () {alert("error");}
);
PHP代码
$db = M('cart');
$pid = I('pid', 0, 'intval');
$cart = array(
'aid' => (int) $_SESSION['uid'],
'pid' => $pid,
'num' => 1
);
$return = array();
// 检查购物车中是否已有相同商品
if ($db->where($cart)->count()) {
$return['status'] = 0;
} else {
$db->add($cart);
$return['status'] = 1;
}
// ajaxReturn()为ThinkPHP框架提供的方法
$this->ajaxReturn($return, 'json');
提交之后数据被插入了数据库,但是回调函数并没有执行,并且alert了error信息。但是我如果使用$.ajax方法却能够正确执行回调函数。
$.ajax({
url : addURL,
async : false,
type : "POST",
data : {pid : id},
dataType : "json",
timeout : 1000,
error : function () {alert("error");},
success : function (data) {
alert("回调函数");
alert(data.status);
}
});
不过,虽然$.ajax提交成功并且正确执行了回调函数,但是在开发人员工具中并不能看到我php控制器的响应(之前用$.post方法提交的时候能够看到控制器的响应)。
对于$.ajax和$.post这种傲娇的行为我实在是不能理解……