【发布时间】:2015-11-01 15:33:58
【问题描述】:
关于我的客户端 jQuery 如何通过服务器端 PHP 处理我的 JSON 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
}
});
}
请注意,在上面的示例中,我必须在我的 PHP 页面中 JSON.parse() responseText 才能将其作为对象处理。它以某种方式将整个 PHP 响应视为一个对象,我必须从该对象中提取 responseText 和 JSON.parse() 才能使用它。
现在这里是我的另一个 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 请求返回的响应得到统一处理。
所以我想我现在的问题是:
- 为什么这两个回调之间存在不一致?
- 哪个更好用?
【问题讨论】: