2010-10-29 120 views
3

使用jQuery.Post發現響應的內容類型有什麼方法嗎?從jQuery.Post獲取響應內容類型

我在模態窗口中有一個窗體,其想法是,如果窗體無效,則會發送一個HTML代碼片段,並將模型的內容替換爲此代碼片段,如果它有效,我想要一個簡單的字符串用於閃光通知的內容(在此使用的類型)。

目前我正在測試返回的字符串是否以「success」開頭,如果是這樣,則使用字符串的其餘部分作爲Flash通知。這顯然是一個很難解決的問題,我真的不喜歡它。

理想情況下,我希望能夠有條件的響應,如果它是「文本/ HTML」,然後插入片段,如果它是「應用程序/ JSON」,那麼我不能只發送消息幫助者,但潛在的其他數據(消息,ID,更具體類型的成功/失敗消息等),這將有助於將來擴展到其他形式。

回答

6

jQuery將已經detect and convert the response based on the content type header(如果在$.ajax()調用中沒有指定type)。例如:if it finds "json" in the content-type header, it'll be an object。你可以這樣做:

$.post("myPage.html", { name: "value" }, function(data) { 
    if(typeof(data) === "string") { 
    //html 
    } else { 
    //JSON 
    } 
}); 

或者,總是傳回JSON,並有通知消息作爲它的屬性,例如:

$.post("myPage.html", { name: "value" }, function(data) { 
    if(data.notification) { 
    showMessage(data.notification); 
    } else { 
    //use the data object 
    } 
}); 
+1

Urgh的typeof,當然要歸功於爲答案。 – Chao 2010-10-29 14:16:05

+0

實際上'type'是'method'的別名。 你的意思是'dataType'我猜... – DUzun 2015-07-13 10:57:54