【问题标题】:Neep help for looping through a particular json data format需要帮助循环遍历特定的 json 数据格式
【发布时间】:2019-11-13 22:13:55
【问题描述】:

我有一些像这样的 json 数据

{"errors":{"toDate":["Date error_message"],"name":["name error_message"]}}

 OR

{"success":{"toDate":["Date update_data"],"name":["name update_data"]}}

如何使用 jQuery、javascript 循环遍历它!

通过ajax请求从服务器返回json数据!

所以如果 json {"errors":....}

我需要显示错误

如果响应成功则更新表行 if 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 的解决方案,但出现以下错误:

未捕获的类型错误:无法读取未定义的属性“错误”

已解决::

我忘记在 ajax 函数中设置 dataType 了!!! 数据类型:json

【问题讨论】:

  • 这些数组总是只有一个元素吗?
  • @Barmar 是的,只有一个元素

标签: javascript jquery json


【解决方案1】:
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]
    }
});

【讨论】:

  • 我收到以下错误:-- Uncaught TypeError: Cannot read property 'errors' of undefined
  • 您是否将 result 替换为包含已解析 JSON 的变量的名称?您应该在 AJAX 调用中使用dataType: 'json',以便 jQuery 自动为您解析。
  • 已解决 :: 我忘了在 ajax 函数中设置数据类型!!! dataType:json 谢谢你的帮助!!
  • 我已经更新了我的答案以适应你的 AJAX 调用。
【解决方案2】:

这里是如何循环 json 对象的示例

var x = {"success":{"toDate":["Date update_data"],"name":["name update_data"]}}
for(key in x){
   console.log(x[key].toDate);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多