Javascript 通过特定json数据格式循环的Neep帮助
我有一些json数据,看起来像这样Javascript 通过特定json数据格式循环的Neep帮助,javascript,jquery,json,Javascript,Jquery,Json,我有一些json数据,看起来像这样 {"errors":{"toDate":["Date error_message"],"name":["name error_message"]}} OR {"success":{"toDate":["Date update_data"],"name":["name update_data"]}} 如何使用jQuery、javascript循环完成此任务 json数据是根据ajax请求从服务器返回的 因此,如果json{“errors”:..} 或者,
{"errors":{"toDate":["Date error_message"],"name":["name error_message"]}}
OR
{"success":{"toDate":["Date update_data"],"name":["name update_data"]}}
如何使用jQuery、javascript循环完成此任务
json数据是根据ajax请求从服务器返回的
因此,如果json{“errors”:..}
或者,如果响应成功,则更新表行,如果json{“success”:…}
这是我的ajax调用函数
jQuery('#juiDialog').on('submit','#formn-update',function(e){
e.preventDefault();
e.stopPropagation();
jQuery.ajax({
Type:'json',
global : false,
async : false,
cache : false,
type : 'POST',
url : jQuery(this).attr('action'),
data:jQuery(this).serialize()
}).success(function(data) {
alert(data.errors.toDate[0]);
});
});
我尝试了@Barmar的解决方案,但出现以下错误:
未捕获的TypeError:无法读取未定义的属性“errors”
已解决::
我忘了在ajax函数中设置数据类型!!!
dataType:json这里是如何循环json对象的示例
jQuery.ajax({
global: false,
async: false,
cache: false,
type: 'POST',
dataType: 'json', // Tell jQuery to parse the JSON result
url: jQuery(this).attr('action'),
data: jQuery(this).serialize()
}).success(function (data) {
if (data.errors) {
alert(data.errors.toDate[0]);
} else {
// do something with data.success.toDate[0] and data.success.name[0]
}
});
var x = {"success":{"toDate":["Date update_data"],"name":["name update_data"]}}
for(key in x){
console.log(x[key].toDate);
}
这些数组总是只有一个元素吗?@Barmar Yes只有一个元素我得到以下错误:-未捕获的TypeError:无法读取未定义的属性“errors”,请用包含已解析JSON的变量名替换
result
?您应该在AJAX调用中使用数据类型:“json”
,以便jQuery将自动为您解析它。已解决::我忘记在AJAX函数中设置数据类型了!!!谢谢你的帮助!!我已经更新了我的答案,以适应您的AJAX调用。