氟利昂的回答大概作品,這裏是一個選擇,請嘗試強制dataType
到JSON。
// This is the signature for $.post
jQuery.post(url [, data] [, success(data, textStatus, jqXHR)] [, dataType])
$.post("api/authenticate", {"authkey": authkey}, function(data){
console.log(data);
if (data.success === "false") {
window.location="/Login.html";
}
}, "json");
另一個想法是要確保您的服務器響應2xx狀態。如果您返回不同的狀態,jQuery
將不會嘗試讀取響應。這反而查找傳遞給http://api.jquery.com/jQuery.ajax/
例
jQuery.ajax("api/authenticate", {
data: {"authkey": authkey},
dataType: 'json',
statusCode: {
306: function(jqXhr, errorType) {
alert('Could not login')
// If you still want to access the response, it's accessible as raw text
// If it's JSON, you have to parse it.
alert (jqXhr.responseText);
}
}
});
我意識到功能(數據)只有在api/authenticate成功時纔會進入。任何想法我能做些什麼來獲得數據時,API調用不成功? – Wilson
ahhh。我發現什麼是錯的。在我的PHP函數中,即使我返回了一個JSON,但我還是以306頁的錯誤返回了它。因此,post方法拒絕了迴應並認爲它不成功。我現在能夠閱讀回覆。謝謝! – Wilson
@Wilson好的,既然你接受了這個答案,我會將這些信息添加到答案本身中,以便將來用戶更容易獲得 –