使用 foreach 函数时的 JavaScript 异常


javascript exception when using foreach function

我正在尝试解析从PHP函数返回的关联数组,如下所示:

$.ajax({
        type: "GET",
        url: "../controllers/Checkpoint.php/getAllCheckpoints"
    }).done(function( result ) {
        result.foreach(function(index, value){
            alert(index + "  "+ value);
        });
    }).error(function(){
    });

我在 PHP 中返回这样的数组

foreach($result as $row) {
            $checkpoints[$row['ID']] = $row['Name'];
        }
        return json_encode($checkpoints);

从 chrome F12 控制台读取该数组的结果是

{"1":"check point 1","2":"check point 2"}

我在javascript代码中收到此错误:

ReferenceError: forEach is not defined

你能帮我吗

我建议将jQuery.each()通用迭代器函数与javascript JSON.parse()结合使用来完成您尝试做的事情。

jQuery.each()

JSON.parse

.done(function( result ) {
    checkpoints = JSON.parse(result);
    $.each( checkpoints, function( index, value) {
         alert(index + "  "+ value);
    });
});

在客户端

您应该使用object.forEach()大写字母e函数或 jQuery 函数$.each(object)

    result.forEach(function(index, value){
        alert(index + "  "+ value);
    });

如果您尚未设置响应标头Content-type: application/json则需要将响应内容解析为对象使用JSON.parse()函数JSON

.done(function( result ) {
    JSON.parse(result).forEach(function(index, value){
        alert(index + "  "+ value);
    });
})

在服务器端

return return并将值分配给任何变量的函数,AJAX响应需要输出缓冲区,以便在服务器端echo内容并在输出缓冲区后终止脚本

    foreach($result as $row) {
        $checkpoints[$row['ID']] = $row['Name'];
    }
    //return json_encode($checkpoints);
    header('Content-type: application/json');
    echo json_encode($checkpoints);
    exit();

header('Content-type: application/json');表示响应内容类型为 JSON 对象

如果你在客户端上有数据,在浏览器上,那么 Php 就没有问题了。当您在客户端上时。Javascript native 不是 for each 的函数,你可以使用 $.each 函数

$.ajax({
    type: "GET",
    url: "../controllers/Checkpoint.php/getAllCheckpoints"
}).done(function( result ) {
    $.each(result, function(i, data){
        console.log(i, data); // this print on console the data that you is run
        // for this you should have installed firebug on firefox or chrome already installed some similar.
    });
}).error(function(){
});

首先:你必须用"echo"而不是"return"返回php结果。