jquery如何检查ajax调用的响应类型

sam*_*sam 71 ajax jquery

如何在Jquery中确定ajax调用的响应类型?有时,服务器发送json响应,有时它只发送html用于显示目的.现在我正在使用

if(response.indexOf('Error'))
  //popup error message
else
 response.username
 response.address
Run Code Online (Sandbox Code Playgroud)

Ank*_*wal 127

你可以这样尝试:

$.ajax({
  type: "POST",
  url: "your url goes here", 
  data: "data to be sent", 
  success: function(response, status, xhr){ 
    var ct = xhr.getResponseHeader("content-type") || "";
    if (ct.indexOf('html') > -1) {
      //do something
    }
    if (ct.indexOf('json') > -1) {
      // handle json here
    } 
  }
});
Run Code Online (Sandbox Code Playgroud)

基本上它也使用indexOf,但似乎更可靠.

  • 顺便说一句,对于任何有兴趣的人,如果你调用`xhr.getResponseHeader()`(没有参数),它会导致'无法调用方法'toLowerCase'的undefined`错误 (2认同)

Imd*_*dad 18

您只需使用javascript的简单方法来检查类型

if(typeof response=="object")
{
 // Response is javascript object
}
else
{
 // Response is HTML
}
Run Code Online (Sandbox Code Playgroud)

如果使用此方法,则不必在成功回调中写入2个额外参数.


tyr*_*ion 9

如果响应被解析为JSON,则该jqXHR对象将具有responseJSON属性.

$.ajax(
    // ...
).done(function(data, textStatus, jqXHR) {
    if (jqXHR.responseJSON) {
        // handle JSON
    } else {
        // handle html
    }
}).fail(function(jqXHR, textStatus, errorThrown) {
    if (jqXHR.responseJSON) {
        // handle JSON
    else {
        // handle html
    }
})
Run Code Online (Sandbox Code Playgroud)

jQuery.ajax文档:

如果指定了json,则在作为对象传递给成功处理程序之前,使用jQuery.parseJSON解析响应.解析的JSON对象通过jqXHR对象的responseJSON属性提供.


小智 8

上面的答案对我没有用,所以我提出了这个解决方案:

success: function(data, textStatus , xhr) {
if(xhr.responseXML.contentType == "text/html") {
    //do something with html
    }
else if(xhr.responseXML.contentType == "application/json") {
    //do something with json
    }}
Run Code Online (Sandbox Code Playgroud)