我有一個JavaScript文件,使AJAX調用服務器上的PHP文件返回JSON編碼數據。 PHP文件可以返回成功或根據與大約十幾個不同的消息,像這樣一個錯誤:Javascript閱讀JSON結果來自AJAX響應
if (something here) {
if(something else here) {
if(more tests here) {
$response['success'] = 'Successfully did something.';
} else {
$response['success'] = 'Successfully made this work';
}
} else {
$response['error'] = 'Failed to make the donuts.';
}
} else {
$response['error'] = 'I need more information!';
}
echo json_encode($response);
exit;
我對所檢查的響應故障情況並顯示一個警告框前端的JavaScript/jQuery的並根據情況執行一些其他相關行動。
$.post(ajaxurl, data, function(response) {
if(response.hasOwnProperty("success")) {
if($(this).is(":checked")) {
$(this).removeAttr("checked");
} else {
$(this).attr("checked", "true");
}
alert(response["success"]);
} else {
alert("Sorry, something went wrong. \nError: " + response["error"]);
}
});
的問題是,無論我如何檢查是否有成功的條件是始終顯示與undefined
一個response['error']
我試圖測試typeOf response['success'] != "undefined"
和一些其他的方式錯誤消息,看是否成功值已設置,但似乎沒有任何工作。我得到一個響應,當我console.log它看起來像這樣:{ "success", "Successfully did something." }
我做錯了閱讀消息?
做console.log響應(檢查是否得到響應)然後if(response.success)不做hasOwnProperty它不是必需的。 – wilsonrufus
你使用哪個版本的jquery? –
其最新版本的jquery,我得到的回覆 – dpegasusm