在ajaxSuccess期间找出响应是否为JSON的理想方法

mko*_*yak 13 javascript ajax jquery

在我的$ .ajaxSucess()函数中,我需要找出响应是否为json.目前我这样做:

$('body').ajaxSuccess(function(evt, xhr, settings) {
    var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/);
    if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){    
...
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

jtf*_*ank 25

假设你期待json,我只是尝试像json一样解析它并捕获任何错误.另请参阅jQuery.parseJSON.

try {
    jQuery.parseJSON(response);
} catch(error) {
    // its not json
}
Run Code Online (Sandbox Code Playgroud)

如果您期望多种不同的响应类型中的一种(即它可能是json或者它可能只是文本等),那么您可能需要变得更复杂.我使用xhr.getResponseHeader("content-type").有关处理内容类型的一些详细信息,请参阅此博客文章.

$.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
        } 
    }
});
Run Code Online (Sandbox Code Playgroud)


Ell*_*son 8

我总是发现以下工作正常:

  if (xhr.getResponseHeader('Content-Type') !== 'application/json') {
    // Something other than JSON was returned
  }
Run Code Online (Sandbox Code Playgroud)

您是否遇到了需要在帖子中添加额外逻辑的情况?

  • 请注意,内容类型也可以包含编码信息.例如'application/json; 字符集= UTF-8' .请参阅[什么"内容类型:application/json; charset = utf-8"真正意味着什么?](http://stackoverflow.com/questions/9254891/what-does-content-type-application-json-charset- UTF-8-真的均值) (2认同)