简体   繁体   English

使用PHP解码JSON字符串时遇到问题

[英]Trouble decoding JSON string with PHP

I'm trying to send an array of objects from JS to PHP using JSON. 我正在尝试使用JSON将对象数组从JS发送到PHP。 I have an array of players as follows: 我有一些玩家,如下所示:

var player;
var players = new Array();
//loop for number of players
player = new Object();
player.id = theID;
players[i] = player;

Then my AJAX call looks like this: 然后我的AJAX调用看起来像这样:

JSONplayers = JSON.stringify(players);
$.ajax({
type: "POST",
url: "php/ajax_send_players.php",
data: {
    "players" : JSONplayers
}

On the PHP side the decode function looks like this 在PHP方面,解码功能如下所示

$players = $_REQUEST['players'];
echo var_dump($players);
$players = json_decode($players);
echo 'players: ' .$players. '--'. $players[0] . '--'. $players[0]->id;

Debugging in chrome, the JSON players var looks like this before it is sent: JSONplayers: "[{"id":"Percipient"},{"id":"4"}]" 在chrome中调试时,JSON播放器var在发送之前看起来像这样:JSONplayers:“ [{” id“:” Percipient“},{” id“:” 4“}]”

And when I vardump in PHP it looks OK, giving this: string(40) "[{\\"id\\":\\"Percipient\\"},{\\"id\\":\\"4\\"}]" 当我在PHP中进行vardump时,它看起来不错,给出以下内容:string(40)“ [{\\” id \\“:\\” Percipient \\“},{\\” id \\“:\\” 4 \\“}]”

But I can't access the PHP array, and the echo statement about starting with players: outputs this: players: ---- 但是我无法访问PHP数组,并且有关以玩家开始的echo语句:输出以下内容:玩家:----

Nothing across the board...maybe it has something to do with the \\'s in the array, I am new to this and might be missing something very simple. 没什么...可能与数组中的\\有关,我对此并不陌生,可能缺少一些非常简单的东西。 Any help would be greatly appreciated. 任何帮助将不胜感激。

note I've also tried json_decode($players, true) to get it as an assoc array but get similar results. 注意我也尝试过json_decode($ players,true)将其作为assoc数组获得,但得到的结果相似。

I tried to emulate some data: 我试图模拟一些数据:

var message = [
    {id: "90"},
    {"id": 123},
    {"id": 456},
    {"id": 87.5},
    {"id": 123.1}
];

I used your javascript and added a success handler to use the output of the PHP file: 我使用了您的JavaScript并添加了成功处理程序以使用PHP文件的输出:

JSONplayers = JSON.stringify(message);
alert(JSONplayers);
$.ajax({
    type: "POST",
    url: "ajaxTest.php",
    data: {
        "players": JSONplayers
    },
    success: function(data) {
        $('#myId').html(data);
    }
}); 

Then I tweeked your PHP a little bit: 然后,我对您的PHP进行了一些调整:

<?php
    $players = $_REQUEST['players'];
    $json = json_decode(stripslashes($players),true);
    foreach($json as $row) {
        echo $row['id'] . '<br />';
    }
?>

This kicks out a new line for each entry and references it by its key (id). 这将为每个条目开一个新行,并通过其键(id)对其进行引用。

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

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