【问题标题】:jQuery: How to iterate through JSON encoded string (array)jQuery:如何遍历 JSON 编码的字符串(数组)
【发布时间】:2015-10-10 09:33:46
【问题描述】:

我是一个 jQuery 初学者,希望有人可以帮助我,也可以给我一些解释。

我有一个 Ajax 调用,它返回一个 JSON 编码的字符串,每个项目都有两个值,一个 itemID 和一个 itemVal - 示例如下所示(使用console.log):

console.log(data) 结果:

string(225) "[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"},...]"

此处的项目数量各不相同,但如果列出了 itemID,则始终存在相应的 itemVal。
itemID 是唯一整数,itemVal 是纯文本。

到目前为止一切正常,但我的问题来了:
对于这里的每个 itemID,我必须对相应的 itemVal 做一些事情,例如说只是将其记录到控制台或提醒它进行测试。

我知道有多种方法可以解决此问题,例如jQuery.each, $.each, for, foreach 等,但由于我最近才开始,我不确定如何迭代此响应。我如何从中选择单个 itemID。

我尝试了不同的方法,包括。 $.parseJSON(data) 失败了,问题似乎是我在解码之前的输入是 二维数组而不是一维数组(我希望我在这里使用正确的术语)导致他们要么返回错误,要么提醒我字符串的每个字符。

更新 - 根据以下答案的失败示例

$.ajax({        
    type: "post",   
    url: "ajax.php",
    cache: "false",
    data: {
        node: 'fetchCountries',
        itemIDs: itemIDs // a list of integers
    },
    success: function(data){
        console.log(data);
        var arr = JSON.parse(data);
        $.each($(arr),function(key,value){
           console.log(value.itemVal);
        });
    }
});

更新 2 - 我的 PHP:

case "fetchCountries":
    $intval_itemIDs = array_map("intval", $_POST["itemIDs"]);
    $itemIDs = implode(",", $intval_itemIDs);

    $stmt = $conn->prepare("SELECT itemID, en FROM Countries WHERE itemID IN(" . $itemIDs . ") ORDER BY itemID");
    $stmt->execute();
    $result = $stmt->get_result();
    while($arrCountries = $result->fetch_assoc()){
        $countries[] = array("itemID" => $arrCountries["itemID"], "itemVal" => $arrCountries["en"]);
    }
    var_dump(json_encode($countries));
    break;

预期结果(用于测试)

console.log("China");
console.log("France");
console.log("Germany");
// ...

有人可以帮我解决这个问题吗?

非常感谢, 蒂姆

【问题讨论】:

  • 它是一个数组或者它是 JSON(“文本”)。不是两者兼而有之。
  • 你是对的,对不起。这是使用 PHP 查询的 Ajax 调用的结果。在 PHP 端,它是一个数组,在我将它发送回 JS 之前,我使用 json_encode - 你可以在我的帖子中看到它的外观。
  • 你使用的是哪个 PHP 版本@WhistleBlower
  • @Uchiha:我可以在 5.4、5.5 和 5.6 之间进行选择,现在已将其设置为 5.6

标签: php jquery arrays foreach each


【解决方案1】:

您有一个表示数组的 JSON 字符串,您将其解析为实际的Array。然后循环遍历数组,将每个元素推入一个新数组 (arr)。

也许有些混乱。希望this 能有所启发。

// Considering the following JSON string:
var data = '[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}]';

// You can create an Array from this like so:
var theArray = JSON.parse(data);

// Now you have an array with each item being an `object`
// with an "itemId" and an "itemVal".  You can loop through
// this array and look at each object like so:
theArray.forEach(function (obj) {
    console.log(obj.itemID + ': ' + obj.itemVal);
});

【讨论】:

  • 非常感谢 - 你的解释是有道理的,但这仍然返回与上述答案相同的错误。在 Chrome 中:“Uncaught SyntaxError: Unexpected token A” - 在 FF 中:“SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data”
【解决方案2】:

WhistleBlower,我已经在我的浏览器上测试了你的代码。有效。为什么不使用 header("Content-type :application/json");也。因此,您不必解析 JSON 字符串。

var data = '[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}]';
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
   console.log(value.itemVal);
});

【讨论】:

  • 也非常感谢!我做了更多的研究,实际上可能就是这样,因为到目前为止所有其他方法都失败了。你能解释一下我必须在哪里以及如何应用它吗?我以前从未使用过它。
  • 看看my comment那里。
  • 你真的需要让你的 JS 变量 arr 成为一个 jQuery 对象吗?你可以试试这个。 $.each(arr, function(key,value){ console.log(value.itemVal); });
【解决方案3】:

你不是在解析一个字符串,你是在解析一个已经解析过的对象

直接用就行了

var data=[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}];

    $.each(data,function(key,value){
        console.log(value.itemVal);
    });

或/

 var arr = JSON.parse(JSON.stringify(data));

    $.each(arr, function (key, value) {
        console.log(value.itemVal);
    });

更新 1:

我认为你的 php 文件就像

    <?php 
      $array = array( array( 'itemID' => 1, 'itemVal' => 'India'), array( 'itemID' => 2, 'itemVal' => 'usa'), array( 'itemID' => 3, 'itemVal' => 'china'), array( 'itemID' => 4, 'itemVal' => 'uk'));
        echo json_encode($array);
//[{"itemID":1,"itemVal":"India"},{"itemID":2,"itemVal":"usa"},{"itemID":3,"itemVal":"china"},{"itemID":4,"itemVal":"uk"}]
     ?>

你的脚本应该是

  $.getJSON( "your.php", function( data ) {
              console.log(data);
                $.each(data, function (key, value) {
                    console.log(value.itemVal);
                });
            });

  $.ajax({        
          type: "post",   
          url: "your.php",
          cache: "false",
          dataType: 'json',
          data: {
              node: 'fetchCountries',
              itemIDs: youval // a list of integers
          },
          success: function(data){
              console.log(data);
                var arr = JSON.parse(JSON.stringify(data));
              $.each($(arr),function(key,value){
                 console.log(value.itemVal);
              });
          }
      });

    $.ajax({        
      type: "post",   
      url: "your.php",
      cache: "false",
      dataType: 'json',
      data: {
          node: 'fetchCountries',
          itemIDs: youval // a list of integers
      },
      success: function(data){
          console.log(data);
          $.each($(data),function(key,value){
             console.log(value.itemVal);
          });
      }
  });

【讨论】:

  • 也非常感谢! - 两种方法都返回一个新错误:“Uncaught TypeError: Cannot use 'in' operator to search 'length'”
  • 使用dataType:'json',让我知道
  • 谢谢。当我使用它时,控制台不会记录任何内容 - 似乎我的 PHP 没有返回任何内容。
  • 感谢和抱歉耽搁了!我刚刚将我的 PHP 添加到帖子中。
  • 我看到你的 php 很好,现在你试试我上面的更新脚本!!
【解决方案4】:

就这么简单!

$.each($(data),function(key,value){
   console.log(value.itemVal); //place alert if you want instead of console.log
});

遍历得到的结果,得到每个itemitemVal

DEMO HERE


更新

dataType 选项添加到ajaxphp 的返回类型应该是json,我希望你这样做!

$.ajax({        
    type: "POST",   
    url: "ajax.php",
    cache: "false",
    dataType:'json', //Add this
    data: {
        node: 'fetchCountries',
        itemIDs: itemIDs // a list of integers
    },
    success: function(data){
        console.log(data);
        var arr = JSON.parse(data);
        $.each($(arr),function(key,value){
           console.log(value.itemVal);
        });
    }
});

从您的php 返回应该是echo json_encode(result);

【讨论】:

  • 试用演示并告诉我!
  • 感谢您的快速回复!它适用于您的演示,但在使用我的代码进行测试时,它只记录单词“Array”。
  • 你能发布更新的代码吗?还有console.log(JSON.parse(data)) + 尝试在控制台中扩展Array 看看你会得到什么!
  • 谢谢 - 刚刚将其添加到帖子中。看起来它仍然将我的数据视为字符串。
  • 您在console.logarr 上得到了什么?如果可能,请发布屏幕截图!
【解决方案5】:

感谢大家对此的帮助。

由于所有其他方法对我来说都有意义但仍然失败,我对此进行了更多研究,最终找到了导致这种情况的原因。

问题确实出在 PHP 方面,在以下帖子中接受的答案起到了作用 - 因为我将它添加到我的 PHP 中,所以 JS 方面的其他一切工作正常,但我没有t 甚至需要 dataType: "JSON" 那里:

dataType: "json" won't work

根据这篇文章,我的案例的解决方案如下 - 感谢 Jovan Perovic:

<?php
//at the very beginning start output buffereing
ob_start();

// do your logic here

// right before outputting the JSON, clear the buffer.
ob_end_clean();

// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>

再次感谢。

【讨论】:

    猜你喜欢
    • 2010-11-17
    • 2018-11-19
    • 2014-04-06
    • 1970-01-01
    • 2019-04-29
    • 2014-06-16
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多