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

时间:2010-10-29 11:39:45

标签: ajax jquery content-type

使用jQuery.Post发现响应的内容类型有没有办法?

我在模态窗口中有一个表单,其思路是如果表单无效,则会发送一个HTML片段,并且该片段的内容将替换为此片段,如果它有效,我想要一个简单的字符串闪光通知的内容(此处使用的类型为SO)。

目前我正在测试返回的字符串是否以“success”开头,如果是,则使用其余字符串作为flash通知。这显然是一个非常糟糕的解决方案,我真的不喜欢它。

理想情况下,我希望能够对响应有条件,如果是“text / html”,则插入片段,如果是“application / JSON”,那么我不仅可以发送消息帮助器,但可能是其他数据(消息,id,更具体类型的成功/失败消息等),这将有助于将来扩展到其他形式。

1 个答案:

答案 0 :(得分: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
  }
});