javascript 在 ajaxSuccess 期间找出响应是否为 JSON 的理想方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7662620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ideal way to find out if response is JSON during ajaxSuccess
提问by mkoryak
In my $.ajaxSucess() function I need to find out if the response is json. Currently I am doing this:
在我的 $.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'){
...
Is there a better way?
有没有更好的办法?
回答by jtfairbank
Assuming that you are expecting json, I'd simply try and parse it like json and catch any errors. Also see jQuery.parseJSON.
假设您期待 json,我只是尝试像 json 一样解析它并捕获任何错误。另请参阅jQuery.parseJSON。
try {
jQuery.parseJSON(response);
} catch(error) {
// its not json
}
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 postfor some great detail on handling content types.
如果您期待多种不同的响应类型中的一种(即它可能是 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
}
}
});
回答by Elliot Nelson
I have always found the following to work just fine:
我一直发现以下方法可以正常工作:
if (xhr.getResponseHeader('Content-Type') !== 'application/json') {
// Something other than JSON was returned
}
Did you run into a situation that required the extra logic in your post?
您是否遇到过需要在您的帖子中添加额外逻辑的情况?
回答by Muhammad Usman
var a={"k":"v"};
var b="k";
try{
$.parseJSON(b);
}catch(e){alert('Not JSON')}
回答by Chris Pietschmann
You could probably use jQuery.parseJSON to attempt parsing it. If an exception is raised then it's not valid json.
您可能可以使用 jQuery.parseJSON 来尝试解析它。如果引发异常,则它不是有效的 json。
回答by Ravi Tayade
If you are expecting the data form ajax response, you could handle it with following ajax call:
如果您期待数据表单 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. <b>Error -404</b>';
} else if (jqxhr.status == 500) {
msg='Internal Server Error <b>Error -500</b>].';
} 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;
}
});