使用 jQuery.Post 时有没有办法发现响应的内容类型?
我在模态窗口中有一个表单,其想法是,如果表单无效,则发送一个 HTML 片段,并将模态的内容替换为该片段,如果有效,我想要一个简单的字符串Flash 通知的内容(SO 上使用的类型)。
目前我正在测试返回的字符串是否以“success”开头,如果是,则使用字符串的其余部分作为闪存通知。这显然是一个相当老套的解决方案,我真的不喜欢它。
理想情况下,我希望能够对响应有一个条件,如果它是“text/html”,则插入片段,如果它是“application/JSON”,那么我不仅可以发送一条消息帮助器,但可能还有其他数据(消息、ID、更具体类型的成功/失败消息等),这将有助于将来扩展到其他形式。
最佳答案
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
}
});
关于ajax - 从 jQuery.Post 获取响应内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4051434/