Php jQuery:如何迭代JSON编码的字符串(数组)

Php jQuery:如何迭代JSON编码的字符串(数组),php,jquery,arrays,foreach,each,Php,Jquery,Arrays,Foreach,Each,我是一个jQuery初学者,希望有人能帮助我,并为我提供一些解释 我有一个Ajax调用,它返回一个JSON编码的字符串,每个项目有两个值,一个itemID和一个itemVal-(使用console.log)示例如下所示: 控制台。日志(数据)结果: string(225) "[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"it

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

我有一个Ajax调用,它返回一个JSON编码的字符串,每个项目有两个值,一个itemID和一个itemVal-(使用
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"},...]"
$.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);
        });
    }
});
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;
<?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));
?>
此处的项目数量有所不同,但如果列出了itemID,则始终会有相应的itemVal。
itemID是唯一的整数,itemVal是纯文本

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

我知道有很多方法可以实现这一点,比如
jQuery.each、$.each、for、foreach
等等。但是由于我最近才开始,我不确定如何迭代这个resp。如何从中选择单个ItemId

我尝试了不同的方法,包括
$.parseJSON(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"},...]"
$.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);
        });
    }
});
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;
<?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));
?>
更新2-我的PHP:

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"},...]"
$.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);
        });
    }
});
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;
<?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));
?>
预期结果(用于测试)

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
});
迭代获得的结果并获得每个
项的
itemVal


更新

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

php
返回的应该是
echo-json\u-encode(结果)

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

也许有一些困惑。希望能给我们一些启示

// 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);
});
您不是在解析字符串,而是在解析已解析的对象

直接用就行了

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

更新1:

console.log("China");
console.log("France");
console.log("Germany");
// ...
我想你的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"}]
     ?>


告密者,我已经在我的浏览器上测试了你的代码。成功了。为什么不使用标题(“内容类型: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方面,下面帖子中的接受答案起到了关键作用——因为我把这个添加到了PHP中,JS方面的其他一切都很好,我甚至不需要数据类型:“JSON”:

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

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"},...]"
$.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);
        });
    }
});
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;
<?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));
?>


再次感谢。

这是一个数组或JSON(“文本”)。不是两者都有,你是对的,对不起。它是使用PHP查询的Ajax调用的结果。在PHP端,它是一个数组,在我将它发送回JS之前,我使用json_encode-你可以在我的帖子中看到它的外观。你使用的是哪个PHP版本@WhistleBlower@Uchiha:我可以在5.4、5.5和5.6之间进行选择,现在已将其设置为5.6试用演示并让我知道!!谢谢你的快速回复!它可以很好地与你的演示,但当测试这个与我的代码,它只记录了字“数组”。你可以张贴更新的代码?还有
console.log(JSON.parse(data))
+尝试在控制台中展开
数组,看看能得到什么!谢谢-刚刚将其添加到帖子中。看起来它仍然将我的数据视为字符串。您在
console.log
arr
上得到了什么?如果可能,发布屏幕截图!非常感谢-您的解释很有道理,但仍然返回与上述答案相同的错误。在Chrome中:“未捕获的SyntaxError:意外标记A”-在FF中:“SyntaxError:JSON.parse:JSON数据第1列第1行的意外字符”也非常感谢这两种方法都返回一个新错误:“uncaughttypeerror:无法使用'in'运算符搜索'length'”使用
dataType:'json',
让我知道谢谢。当我使用它的时候,控制台不会记录任何东西——我的PHP似乎不会返回任何东西。谢谢,很抱歉延迟了!我刚刚将我的PHP添加到帖子中。我看到你的PHP很好,现在你可以试试上面我更新的脚本!!也非常感谢!我做了更多的研究,实际上可能就是这样,因为所有其他方法都失败了。你能解释一下我在哪里以及如何应用这个吗?我以前从未使用过它。看看那里。你真的需要把你的JS变量arr变成jQuery对象吗?你可以试试这个。$.each(arr,函数(键,值){console.log(value.itemVal);});