Javascript JSON to PHP Array


Javascript JSON to PHP Array

在我的Javascript中,我像这样组装和数组:

    cachePHP = "'lat':'" + (Number(upDataItems[2])).toFixed(5)+"'";
cachePHP = cachePHP + ",'lon':'" + (Number(upDataItems[3])).toFixed(5)+"'";
cachePHP = cachePHP + ",'msec':'" + (parseInt(upDataItems[7])-parseInt(tz))+"'";
cachePHP = cachePHP + ",'spd':'" + (Number(upDataItems[0])).toFixed(1)+"'";
cachePHP = cachePHP + ",'hdg':'" + (Number(upDataItems[1])).toFixed(1)+"'";
dataCacheNew.push("{"+cachePHP+"}");

我向数组中添加了不同数量的数据,可以是10项,可以是100项…然后把它放到一个PHP文件中。PHP文件从Javascript中调用,如下所示:

"my.php?che="+JSON.stringify(dataCacheNew);

在PHP中,我如何获取数据,以便我可以"解析"它并将其发布到我的数据库?

03/13更新:我还是搞不定这玩意。根据以下建议更新,仍然……没有workie !

My Javascript (jQuery):

     var jsonData = new Array();
    jsonData.push({
    lat: Number(56.34).toFixed(2),
    lon: Number(12.56).toFixed(2),
    msec: Number(123456799000).toFixed(2),
    spd: Number(4.2).toFixed(2),
    hdg: Number(1.4).toFixed(2)
}); 
jsonData.push({
    lat: Number(12.34).toFixed(2),
    lon: Number(34.56).toFixed(2),
    msec: Number(123456789000).toFixed(2),
    spd: Number(1.2).toFixed(2),
    hdg: Number(3.4).toFixed(2)
});

    $.ajax({
        url: 'insertCache.php',
        type: 'POST',
        data: "che="+JSON.stringify(jsonData),
        dataType: 'json',
        contentType: "application/json",
        success: function(result) {
            alert(result);
        }
    });

我的PHP:

$cache = $_POST['che'];
    writeData($cache,"insertCache.txt");
$cacheDecode = json_decode($cache);
writeData($cacheDecode,"insertCacheDecode.txt");

insertCache.txt:

[{'"lat'":'"56.34'",'"lon'":'"12.56'",'"msec'":'"123456799000.00'",'"spd'":'"4.20'",'"hdg'":'"1.40'"},{'"lat'":'"12.34'",'"lon'":'"34.56'",'"msec'":'"123456789000.00'",'"spd'":'"1.20'",'"hdg'":'"3.40'"}]

insertCacheDecode.txt完全空白

给了什么?

您可以使用如下代码:

$array = json_decode($_GET['che']);

请注意,您不需要创建字符串,您可以将嵌套对象字符串化:

dataCacheNew.push({
    lat: (Number(upDataItems[2])).toFixed(5),
    lon: (Number(upDataItems[3])).toFixed(5),
    msec: (parseInt(upDataItems[7])-parseInt(tz)),
    spd: (Number(upDataItems[0])).toFixed(1),
    hdg: (Number(upDataItems[1])).toFixed(1)
});

不要尝试自己构建JSON字符串。语言对此有内置的方法。而是按照你想要的方式构建对象,然后将其编码为JSON。

var cachePHP = {
    lat: (Number(upDataItems[2])).toFixed(5),
    lon:(Number(upDataItems[3])).toFixed(5),
    msec: (parseInt(upDataItems[7])-parseInt(tz)),
    spd: (Number(upDataItems[0])).toFixed(1),
    hdg: (Number(upDataItems[1])).toFixed(1),
};
dataCacheNew.push(cachePHP);
console.log(JSON.stringify(dataCacheNew));

你的JSON是无效的,因为你使用单引号为你的属性名。最重要的是,你在对已经编码不好的JSON进行字符串化。

使用下面的

dataCacheNew.push({
    lat: Number(upDataItems[2]).toFixed(5),
    lon: Number(upDataItems[3]).toFixed(5),
    ...
});
"my.php?che=" + JSON.stringify(dataCahceNew);