在ajaxSuccess期间找出响应是否为JSON的理想方法 [英] Ideal way to find out if response is JSON during ajaxSuccess

查看:65
本文介绍了在ajaxSuccess期间找出响应是否为JSON的理想方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的$ .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'){    
...

有更好的方法吗?

推荐答案

假设您期待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(content-type)。有关处理内容类型的一些非常详细的信息,请参见此博客文章

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屋!

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