jQuery的如何检查响应类型的Ajax调用 [英] jquery how to check response type for ajax call

查看:161
本文介绍了jQuery的如何检查响应类型的Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何确定在jQuery中Ajax调用的响应类型?有时,服务器发送JSON响应,有时也只发送HTML用于显示。现在我用

 如果(response.indexOf(错误))
  //弹出错误信息
其他
 response.username
 response.address
 

解决方案

您可以尝试这样的:

  $。阿贾克斯({
  键入:POST,
  网址:您的网址放在这里,
  数据:数据要发送,
  成功:函数(响应状态,XHR){
    VAR克拉= xhr.getResponseHeader(内容类型)|| ;
    如果(ct.indexOf(HTML)> -1){
      //做一点事
    }
    如果(ct.indexOf(JSON)GT; -1){
      //这里处理JSON
    }
  }
});
 

基本上它也是使用的indexOf但它似乎更可靠。

How can I determine the response type of ajax call in Jquery? At times, the server sends json response and at times it sends only the html for display purposes. Right now I am using

if(response.indexOf('Error'))
  //popup error message
else
 response.username
 response.address

解决方案

You can try it like:

$.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
    } 
  }
});

Basically it is also using indexOf but it seems more reliable.

这篇关于jQuery的如何检查响应类型的Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆