php检索多个json对象数组

php retrieving multiple arrays of json objects

本文关键字:对象 数组 json 检索 php      更新时间:2024-05-07

我正在向数据库中发送一组JSON对象。它们保存为:

function send_custom_markers() {
    var reponse = confirm("Send markers to selected contacts?");
    if (reponse === true)
    {
        var json_markers = new Array();
        for (var i = 0; i < myCustomMarkers.length; i++) {
            json_markers.push({
                title: myCustomMarkers[i].getTitle(),
                lat: myCustomMarkers[i].getPosition().lat(),
                lng: myCustomMarkers[i].getPosition().lng(),
                img: myCustomMarkers[i].getIcon(),
            });
        }
        json_markers = JSON.stringify(json_markers);
        $.ajax({
            type: 'post',
            url: 'dist/backend/action_controller.php',
            data: {action: "send_custom_markers", userID: userID, data: json_markers},
            success: function() {
                alert("Markers Sent");
            }
        });
    }
}

我知道这部分是有效的,因为在数据库中它们看起来像这样:

[{"title":"Marker: 1","lat":37.6637114...

现在我需要把它们都弄出来。

Php代码:

$result = $this->query($sql);
$friends_markers = array();
while ($row = $result->fetch_array()) {
    $friends_markers[] = json_encode($row, true);
    //Something needs to go here.
}
echo $friends_markers;      

和JavaScript代码:

function get_friends_custom_markers(userID) {
    $.ajax({
        type: 'post',
        url: 'dist/backend/action_controller.php',
        dataType: 'json',
        data: {action: "get_friends_custom_markers", userID: userID},
        success: function(friends_markers) {
            alert(friends_markers[0][0].title);
        },
        error: function(xhr, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}  

我把警报放在那里只是为了测试结果。

我的逻辑是,对于每个用户,他们都保存了一个JSON对象数组。为了把它们都取出来,我需要一个数组,它的每个元素都是JSON对象的数组。所以如果我这样做:

alert(friends_markers[0][0].title);

输出应为:

"Marker: 1"

但我得到了

200
parsererror

我知道在$result之前一切正常。我知道问题出在php函数中的while循环中。我试过很多不同的东西,但都不管用。这花了我好几天的时间。我是php和JavaScript的新手。这是我正在做的项目的最后一部分。一旦我可以把所有的东西放在一个数组中,然后我就可以把它们都画到谷歌地图上。所以任何事情都会有帮助。谢谢

通过在success()回调中使用console.log(friends_markers)将friends_markers转储到浏览器的调试控制台,您应该能够更好地了解ajax调用的结果。目前所有的浏览器都附带了控制台,尽管每种浏览器的使用方式不同。