在ajaxSuccess期间找出响应是否为JSON的理想方法
Ideal way to find out if response is JSON during ajaxSuccess
在我的$. ajaxsuccess()函数中,我需要找出响应是否为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
}
你是否遇到了需要在你的帖子中添加额外逻辑的情况?
var a={"k":"v"};
var b="k";
try{
$.parseJSON(b);
}catch(e){alert('Not JSON')}
您可以使用jQuery。parseJSON来尝试解析它。如果引发异常,则该文件无效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. <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;
}
});
相关文章:
- jQuery匹配JSON对象的部分文本
- 在循环中分配json值时,值被覆盖
- 需要帮助设置json数组
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 使用JQuery解析JSON嵌套数组
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 如何使用json将对象列表从java转换为javascript
- 如何使用 node.js 比较两个 json 数组
- 如何将JSON数据导入我的ejs模板
- 区分JSON中的矩阵和列表列表
- 不显示带有本地json文件数据的谷歌地图脚本
- 如何将json数据显示为html
- 如何为json对象中的段发送array[]
- 根据id将json数组组合为一个json数组
- Json数据包含日期和时间格式
- AngularJS-在JSON选择器中使用变量名
- 在ajaxSuccess期间找出响应是否为JSON的理想方法