我对客户端jQuery如何通过服务器端PHP处理我的JSON ajax响应有一些不一致。为什么有时我需要JSON.parse()我的AJAX响应?
这里有两个例子Ajax调用我有:
function checkOrders() {
$.ajax({
type: "POST" ,
url:"/service/index.php" ,
data: {
q: "checkOrders"
} ,
complete: function(result) {
// note here the JSON.parse() clause
var x = JSON.parse(result.responseText);
if (x['unhandled_status']>0) {
noty({
text: '<center>There are currently <b>'+x['unhandled_status']+'</b> unhandled Orders.',
type: "information",
layout: "topRight",
modal: false ,
timeout: 5000
}
});
}
} ,
xhrFields: {
withCredentials: true
}
});
}
注意在上面的例子中,我必须JSON.parse()
的responseText
从我的PHP页面,以对付它作为一个对象。它以某种方式将整体PHP响应视为一个对象,为了使用它,我必须从该对象中取出responseText
,并将其取出。
现在这里是另一个ajax调用,我有,返回的响应,我可以直接用作json响应 - 意思是,PHP页面不会返回完整的“对象”,但只返回json和我的ajax调用多少已经知道它是JSON,我并不需要它JSON.parse()
:
function getUnfiledOrders() {
$.ajax({
type: "POST" ,
url:"/service/index.php" ,
data: {
queryType: "getUnfiledOrders"
} ,
success: function(result) {
if (result['total_records'] >0) {
noty({
text: result['response'],
type: "error",
modal: false,
dismissQueue: true,
layout: "topRight",
theme: 'defaultTheme'
});
}
} ,
xhrFields: {
withCredentials: true
}
});
}
在这种情况下,我并不需要JSON.parse()来的responseText
为了治疗的响应作为JSON对象。
两个PHP脚本响应这个样子:
header('content-type:application/json');
$array = array("total_records"=>3,"response"=>"SUCCESS");
echo json_encode($array);
能
有人给我介绍的这种不均匀性?
编辑:
我意识到,我在上述各Ajax调用的有两个不同的回调。一个在complete
上,另一个在success
上。
当我将它们切换到success
时,从我的ajax请求返回的响应被统一处理。
所以我想我现在的问题是:
- 为什么会出现这两个回调之间的非均匀性?
- 哪个更好用?
这将真正有助于解释为什么这是downvoted仅被调用。它确实解决了你的问题,对吧?纠正我,如果我错了... –
我没有downvote它.... –
ajax如何调用$ .getJSON调用?也许你可以更好地解释这一点。它是否总是导致一个对象反对$ .ajax()调用?再一次,我没有倒下你...... –