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

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

有没有更好的办法?

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

 try { jQuery.parseJSON(response); } catch(error) { // its not json } 

如果您期望许多不同的响应类型之一(即它可能是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 } } }); 

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

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

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

 var a={"k":"v"}; var b="k"; try{ $.parseJSON(b); }catch(e){alert('Not JSON')} 

您可以使用jQuery.parseJSON来尝试解析它。 如果引发exception,则它不是有效的json。

http://api.jquery.com/jQuery.parseJSON/

如果您希望数据形成ajax响应,则可以通过以下ajax调用来处理它:

 $.ajax({ dataType: "json", //dataType is important type: 'post', url: orifinalurl, data: reqParam, }).done(function(data){ //response is valid json data. }).error(function(jqxhr, exception){ if (jqxhr.status === 0) { msg='Can not connect to server. Please check your network connection'; } else if (jqxhr.status == 404) { msg='Requested page not found. Error -404'; } else if (jqxhr.status == 500) { msg='Internal Server Error Error -500].'; } else if (exception === 'parsererror') { msg='Requested JSON parse failed.'; } else if (exception === 'timeout') { msg='Request Time out error.'; } else if (exception === 'abort') { msg='Request aborted.'; } else { msg='Uncaught Error.n' + jqxhr.responseText; } });