jQuery:如何遍历JSON编码的字符串(数组)

jQuery: How to iterate through JSON encoded string (array)

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

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

console.log(数据) 结果:

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 等。但是由于我最近刚开始,所以我不确定如何遍历此 resp。我如何 select 从中获取单个 itemID。

我尝试了不同的方法,包括。 $.parseJSON(data) 失败了,问题似乎是我在解码之前的输入是 二维数组而不是一维数组 (我希望我使用的是正确的此处的术语)导致它们 return 出错或提醒我的字符串中的每个字符。

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

$.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");
// ...

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

非常感谢, 蒂姆

就这么简单!

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

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

itemVal

DEMO HERE


更新

dataType 选项添加到您的 ajax 并且 php 中的 return 类型应该是 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);
        });
    }
});

和 return 来自你的 php 应该是 echo json_encode(result);

您有一个表示数组的 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);
});

You're not parsing a string, you're parsing an already-parsed object

直接用就行了

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);
          });
      }
  });

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);
});

感谢大家对此的帮助。

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

问题确实在 PHP 方面,接受了以下 post 的答案 - 因为我将其添加到我的 PHP JS 方面的其他一切工作正常,我什至不需要数据类型:"JSON" 那里:

dataType: "json" won't work

根据这个 post 我的案例的解决方案如下 - 感谢 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));
?>

再次感谢。