jquery how to check response type for ajax call

后端 未结 5 726
孤街浪徒
孤街浪徒 2020-12-04 13:57

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

5条回答
  •  遥遥无期
    2020-12-04 14:40

    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.

提交回复
热议问题