【问题标题】:Looping through Dynamic JSON String循环通过动态 JSON 字符串
【发布时间】:2011-07-24 12:31:54
【问题描述】:

我有一个 POST 请求,它收到一个 JSON 字符串作为结果。字段、值或数组有多深?这些都是未知数。所以,我需要遍历每个 json 值、它的索引和它的值,并基于它执行操作。

$.post(
    "test.php", 
    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function() {
       key = data.key; //i need to retrieve the key
       value = data.value; //i need to retrieve the value also

       //now below here, I want to perform action, based on the values i got as key and values
      }
    },
    "json"
);

如何获取分隔为keyvalue 的JSON 值?

【问题讨论】:

    标签: jquery json


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      对不起,伙计们,但我自己解决了。请不要生我的气。 (如果社区需要,我会删除问题。)

      $.post(
          "test.php", 
          { action: 'someaction', param: '2' },
          function(data) {
            //now data is a json string
            $.each(data, function(key,value) {
             alert(key+value);
             //now below here, I want to perform action, based on the values i got as key and values
            }
          },
          "json"
      );
      

      【讨论】:

      • 感谢您发布您的解决方案。你应该选择这个作为答案。
      【解决方案3】:

      嗯,JSON 被解析为 JavaScript 对象。您可以使用for...in 遍历它们:

      for(var key in data) {
          if(data.hasOwnProperty(key)) {
              var value = data[key];
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-11-23
        • 2017-03-21
        • 2020-05-04
        • 2017-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-22
        • 1970-01-01
        相关资源
        最近更新 更多