ajax - 从 jQuery.Post 获取响应内容类型

标签 ajax jquery content-type

使用 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/

相关文章:

python - 从类似文件确定文件/内容/mime 类型?

javascript - 为什么我的服务器没有收到任何内容?

javascript - JS & Node : Read table from DB with AJAX and display in table

javascript - 当用户垂直滚动或单击底部导航选项卡之一时,如何制作显示下一张幻灯片的内容 slider ?

internet-explorer - jquery.ajax post 请求在 IE9 中缺少内容类型,在 Chrome 中有效

jquery - 用于更改特定幻灯片颜色的视差导航菜单

javascript - JQuery Click 处理程序仅适用于第一个项目

c# - 使用 Ajax POST 将 Javascript 数组传递到 C# 代码隐藏

javascript - JSONP请求链接到用户输入字段+按钮: only executes once

ajax - AJAX使Chrome崩溃