简体   繁体   English

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

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

I am a jQuery beginner and hope someone can help me with this and also provide me some explanations. 我是jQuery的初学者,希望有人可以帮助我解决这个问题,并提供一些解释。

I have an Ajax call that returns a JSON encoded string with two values for each item, an itemID and an itemVal - an example looks as follows (using console.log ): 我有一个Ajax调用,它返回一个JSON编码的字符串,其中每个项目都有两个值,一个itemID和一个itemVal- 示例如下 (使用console.log ):

console.log(data) result: 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"},...]"

The number of items here varies but if an itemID is listed than there is always a corresponding itemVal. 此处的项目数量有所不同,但如果列出了itemID,则总会有一个对应的itemVal。
itemID is a unique integer, itemVal is plain text. itemID是唯一的整数,itemVal是纯文本。

Everything works so far but here comes my problem: 到目前为止一切正常,但是我的问题来了:
For each itemID here I have to do something with the corresponding itemVal , eg say just log it to the console or alert it for testing. 对于这里的每个itemID,我必须对相应的itemVal做一些事情 ,例如说只需将其记录到控制台或提醒它进行测试。

I know there are various approaches for this like jQuery.each, $.each, for, foreach etc. but since I just started recently I am not sure how I can iterate through this resp. 我知道有很多方法可以解决这个问题,例如jQuery.each, $.each, for, foreach等。但是由于我最近才开始,所以我不确定如何遍历此响应。 how I can select the single itemIDs from it. 如何从中选择单个itemID。

I tried different approaches, incl. 我尝试了不同的方法,包括 $.parseJSON(data) which failed and it seems the problem is that my input before being decoded is a two-dimensional array instead of a one-dimensional one (I hope I am using the right terms here) which caused them to either return an error or to alert every single character of my string. $.parseJSON(data)失败了,看来问题是我的输入在解码之前是二维数组而不是一维数组 (我希望我在这里使用正确的术语),这导致它们返回错误或警告我字符串的每个字符。

Update - failing example as per the answer below 更新-根据以下答案的失败示例

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

Update 2 - My PHP: 更新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;

Expected outcome (for testing) : 预期结果 (用于测试)

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

Can someone help me with this ? 有人可以帮我弄这个吗 ?

Many thanks, Tim 非常感谢,蒂姆

You have a JSON string representing an Array, which you are parsing into an actual Array . 您有一个表示Array的JSON字符串,您正在将其解析为实际的Array Then you are looping through the array, pushing each element into a new Array ( arr ). 然后,您遍历数组,将每个元素推入新的Array( arr )。

Perhaps there is some confusion. 也许有些混乱。 Hopefully this will shed some light. 希望会有所启发。

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

WhistleBlower, I have tested your code on my browser. WhistleBlower,我已经在浏览器上测试了您的代码。 It worked. 有效。 Why don't you use header("Content-type :application/json"); 你为什么不使用header(“ Content-type:application / json”); too. 太。 So, you will not have to parse your JSON string. 因此,您将不必解析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);
});

As simple as this! 就这么简单!

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

iterate through the obtained result and get itemVal value of each item 迭代获得的结果并获取每个item itemVal

DEMO HERE 此处演示


UPDATE 更新

Add dataType option to your ajax and return type from php should be json and I hope you are doing that! dataType选项添加到您的ajax并且从php返回的类型应为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);
        });
    }
});

and return from your php should be echo json_encode(result); 并从您的php返回应该是echo json_encode(result);

You're not parsing a string, you're parsing an already-parsed object 您不是在解析字符串,而是在解析一个已经解析的对象

just use it directly 直接使用

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

or/ 要么/

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

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

Update 1: 更新1:

I think so your php file like 我认为您的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"}]
     ?>

your script should be 您的脚本应该是

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

OR 要么

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

OR 要么

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

Thanks to everyone for the help with this. 感谢大家的帮助。

Since all other approaches made sense to me but still failed I did some more research on this and finally found what was causing this. 由于所有其他方法对我来说都是有意义的,但仍然失败,因此我对此进行了更多研究,最终找到了造成此问题的原因。

The issue was indeed on the PHP side and the accepted answer on the following post did the trick - since I added this to my PHP everything else on the JS side is working fine and I don't even need the dataType: "JSON" there: 问题的确在PHP方面, 下面的帖子中接受的答案起到了作用-因为我将其添加到了PHP中,所以JS方面的其他所有东西都工作正常,我什至不需要dataType:“ JSON” :

dataType: "json" won't work dataType:“ json”将不起作用

As per this post the solution for my case is the following - kudos to Jovan Perovic: 根据这篇文章,我的情况的解决方案如下-赞扬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));
?>

Thanks again. 再次感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM