如何确定Jquery中ajax调用的响应类型?有时,服务器发送json响应,有时仅发送html以供显示.现在我正在使用
if(response.indexOf('Error'))
//popup error message
else
response.username
response.address
如何确定Jquery中ajax调用的响应类型?有时,服务器发送json响应,有时仅发送html以供显示.现在我正在使用
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
}
}
});
基本上,它也在使用indexOf,但似乎更可靠.