最好的办法,以找出是否响应的ajaxSuccess期间JSON [英] best way to find out if response is json during ajaxSuccess
问题描述
在我的$ .ajaxSucess()函数,我需要找出是否响应是JSON。目前我在做这样的:
in my $.ajaxSucess() function i need to find out if the response is json. currently i am doing this:
$('body').ajaxSuccess(function(evt, xhr, settings) {
var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/);
if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){
...
有没有更好的办法?
is there a better way?
推荐答案
假设你期待JSON,我会简单地尝试并解析它像JSON和捕捉任何错误。另请参见 jQuery.parseJSON 。
Assuming that you are expecting json, I'd simply try and parse it like json and catch any errors. Also see jQuery.parseJSON.
try {
jQuery.parseJSON(response);
} catch(error) {
// its not json
}
如果你期待的一些不同的反应类型(例如,它可能是JSON或它可能只是文字,等等),那么你可能需要变得更加复杂。我会用xhr.getResponseHeader(内容类型)。请参见这篇博客一些伟大的细节上处理的内容类型。
If you are expecting one of a number of different response types (i.e. it might be json or it might just be text, etc) then you might need to get more complicated. I'd use xhr.getResponseHeader("content-type"). See this blog post for some great detail on handling content types.
$.ajax({
type: "POST",
url: "/widgets",
data: widgetForm.serialize(),
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf(‘html’) > -1) {
widgetForm.replaceWith(response);
}
if (ct.indexOf(‘json’) > -1) {
// handle json here
}
}
});
这篇关于最好的办法,以找出是否响应的ajaxSuccess期间JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!