[英]jQuery $.ajax done callback not firing
我有以下代碼:
$("#loginSubmitButton").on("click",function(){
var loginUserDetails = {
email: $("#email").val(),
password: $("#password").val()
};
//Send the AJAX request to authenticate the user
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: JSON.stringify(loginUserDetails),
contentType: "application/json;charset=UTF-8",
dataType: "json",
}).done(function() {
$("#loginResult").text("Login successful");
})
.fail(function() {
$("#loginResult").text("Login failed");
});
});
根據 jquery 文檔(除非我理解錯誤),如果我從我的 Web 服務器收到 200 OK,我希望 done 被觸發。 但是,在 chrome 控制台中,我可以看到 200 OK 響應,但 jquery 似乎觸發了失敗處理程序。
有誰知道我在這里可能做錯了什么?
您需要刪除:
dataType: "json"
有很多建議可以刪除
dataType: "json"
雖然我承認這是有效的,但它可能忽略了潛在的問題。 這很可能是由解析器錯誤(瀏覽器解析 json 響應)引起的。 首先檢查 .always() 或 .fail() 中的 XHR 參數。
假設它是一個解析器失敗,那么為什么? 也許返回字符串不是 JSON。 或者它可能是響應開始時的錯誤空格。 考慮在 fiddler 中查看它。 我的看起來像這樣:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
就我而言,這是 PHP 噴出不需要的字符(在這種情況下為 UTF 文件 BOM)的問題。 一旦我刪除了這些,它就解決了問題,同時還保持
dataType: json
如果您的服務器為 json 響應返回空字符串(即使是 200 OK),jQuery 會將其視為失敗。 從 v1.9 開始,空字符串被認為是無效的 json。
無論是什么原因,一個值得關注的地方是傳遞給回調的“數據”參數:
$.ajax( .. ).always(function(data) {
console.log(JSON.stringify(data));
});
它的內容將使您了解問題所在。
需要刪除 , from dataType: "json",
dataType: "json"
ajax URL 必須是同一個域。 您不能使用 AJAX 訪問跨域腳本。 這是因為同源策略。
添加“dataType:JSONP”實現跨域通信
使用下面的代碼
$.ajax({
URL: cross domain
dataType: 'jsonp'
// must use dataType:JSONP to achieve cross domain communication, otherwise done function would not called.
// jquery ajax will return "statustext error" at }).always(function(data){}
}).always(function(data){
alert(JSON.stringify(data));
}
一些應該可以解決您的問題的事情以及一些提示。
不要聽點擊提交按鈕。 您應該等待表單上的提交事件。
$.ajax
的data
選項不需要 JSON 字符串。 它需要一個序列化的字符串或一個帶有名稱和值對象的數組。 您可以使用.serialize()
或.serializeArray()
輕松創建其中任何一個。
這是我對你的腳本的想法。
$('#form-with-loginSubmitButton').on('submit', function(e){
e.preventDefault():
var $form = $(this),
data = $form.serializeArray();
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: data
}).done(function(result){
console.log(result);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.