2010-06-18 80 views
9

我們編寫了一個RESTful服務器API。無論出於何種原因,我們都決定,對於DELETE,我們希望返回一個204(無內容)狀態碼,並帶有空的響應。我試圖從jQuery的調用此方法,傳遞一個成功處理程序和設置動詞DELETE:

jQuery.ajax({ 
    type:'DELETE', 
    url: url, 
    success: callback, 
}); 

服務器返回一個204,但成功處理程序不會被調用。有沒有一種方法可以配置jQuery以允許204s激發成功處理程序?

回答

11

204應成功治療。你使用的是什麼版本的jQuery?我做了一些測試,所有200個距離狀態代碼都發送到成功處理程序。爲jQuery 1.4.2該人士證實了這一點:

// Determines if an XMLHttpRequest was successful or not 
httpSuccess: function(xhr) { 
    try { 
     // IE error sometimes returns 1223 when 
     // it should be 204 so treat it as success, see #1450 
     return !xhr.status && location.protocol === "file:" || 
      // Opera returns 0 when status is 304 
      (xhr.status >= 200 && xhr.status < 300) || 
      xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; 
    } catch(e) {} 

    return false; 
}, 
+0

好吧,現在我很困惑。我再次嘗試這個,它似乎正在工作。看起來我一定是在做其他不正確的事情。 謝謝! – Bennidhamma 2010-06-20 19:25:27

3
jQuery.ajax({ 
    ... 
    error: function(xhr, errorText) { 
     if(xhr.status==204) successCallback(null, errorText, xhr); 
     ... 
    }, 
    ... 
}); 

難看......但可能有助於

+0

謝謝sje397,這是有道理的。你認爲這是唯一的方法? – Bennidhamma 2010-06-18 17:45:36

9

我有一個simliar問題,因爲我的劇本也被髮送「的Content-Type」頭爲「應用/ JSON」。當請求成功時,它不能JSON.parse一個空字符串。

2

這在技術上是你的服務器
就像保羅說,一個空的204響應與服務器內容類型的JSON是的jQuery視爲錯誤的問題。

你可以通過手動覆蓋dataType爲'text'來解決jQuery中的問題。

$.ajax({ 
    url: url, 
    dataType:'text', 
    success:(data){ 
     //I will now fire on 204 status with empty content 
     //I have beaten the machine. 
    } 
}); 
2

這是成功回調的替代方式......我認爲這對您有用。

$.ajax({ 
    url: url, 
    dataType:'text', 
    statusCode: { 
       204: function (data) { 
        logic here 
       } 
}); 
相關問題