2

在我的 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 文件中。从 Javascript 调用 PHP 文件,如下所示:

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

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

更新 03/13:我仍然无法让它工作。根据以下建议更新,但仍然......没有工作!

我的 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");

插入缓存.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 完全空白

是什么赋予了?

4

3 回答 3

4

你可以使用这样的代码:

$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)
});
于 2013-03-12T20:01:05.397 回答
2

不要尝试自己构建 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));
于 2013-03-12T20:06:45.737 回答
1

您的 JSON 无效,因为您使用单引号作为属性名称。最重要的是,您正在对编码错误的 JSON 进行字符串化。

改用以下内容

dataCacheNew.push({
    lat: Number(upDataItems[2]).toFixed(5),
    lon: Number(upDataItems[3]).toFixed(5),
    ...
});
"my.php?che=" + JSON.stringify(dataCahceNew);
于 2013-03-12T20:05:05.210 回答