我對客戶端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()調用?再一次,我沒有倒下你...... –