如何在Jquery中确定ajax调用的响应类型?有时,服务器发送json响应,有时仅发送用于显示的html。现在我正在使用
if(response.indexOf('Error'))
//popup error message
else
response.username
response.address
发布于 2010-09-18 19:54:11
您可以像这样尝试:
$.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,但它似乎更可靠。
发布于 2012-07-05 18:17:17
您可以简单地使用javascript的简单方法来检查类型
即
if(typeof response=="object")
{
// Response is javascript object
}
else
{
// Response is HTML
}
如果你使用这个方法,你不需要在成功回调中写2个额外的参数。
发布于 2011-12-09 20:57:39
上面的答案对我不起作用,所以我想出了这个解决方案:
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
}}
https://stackoverflow.com/questions/3741574
复制相似问题