json字符串的Javascript帖子:没有任何传入或返回

时间:2015-04-01 19:55:33

标签: javascript php jquery html json

我正在处理从html表中获取数据的页面(两列加上表单的索引)并生成一个json字符串。这应该传递到php,然后我对数据进行一些计算,然后将其发送回页面以附加具有新列值的表。

这是我到目前为止所得到的:

数据阵列

这是其中一个数组的样子(LatData):

[1, 1, "43.07104167", "43.07178767", "43.0707977", "43.07115595", "43.06975769", "43.07023291", "43.07269194", "43.07112776", "43.07067623", "43.07285063", "43.07132924", "43.07091389", "43.07218128", "43.07279775", "43.07440354", "43.07560161", "43.07471769", "43.07073611", "43.07067713", "43.070925", "43.07148333", "43.07070833", "43.07046389", "43.07024444", "43.07127778"]

将数组和int转换为JSON字符串

所以我采用两个数组,比如上面一个相同长度的数组,而Item只是一个单值整数,我制作了我的json字符串:

json = JSON.stringify({"Item":Item, "Lat": LatData, "Lon": LongData}); 

然后我得到一个很好的json字符串,如下所示:

{"Item":1,"Lat":[1,1,"43.07104167","43.07178767","43.0707977","43.07115595","43.06975769","43.07023291","43.07269194","43.07112776","43.07067623","43.07285063","43.07132924","43.07091389","43.07218128","43.07279775","43.07440354","43.07560161","43.07471769","43.07073611","43.07067713","43.070925","43.07148333","43.07070833","43.07046389","43.07024444","43.07127778"],"Lon":[1,1,"-99.325375","-99.32837458","-99.32465527","-99.325341","-99.32509187","-99.32417542","-99.32573126","-99.32726626","-99.32830531","-99.32749062","-99.32966364","-99.32493056","-99.33109478","-99.33023795","-99.32853197","-99.32776487","-99.32631851","-99.3253","-99.32540699","-99.32571944","-99.32540278","-99.32453889","-99.32566667","-99.32622222","-99.32622222"]}

将JSON字符串发送到PHP

以下是我发布数据的方式:

function MakePhpCall()
{

var json ="";  //this is the JSON string of all the data
var Item=1;    //holding this constant for now

json = JSON.stringify({"Item":Item, "Lat": LatData, "Lon": LongData});  //make JSON string to pass into PHP

if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("response").innerHTML = xmlhttp.responseText;
        }
    }
   xmlhttp.open("GET","Conversion_JQ.php?json=" + json, true);      

    xmlhttp.send();
}

PHP处理程序

然后在PHP方面我这样做:

$positions = json_decode($json);
echo $positions->Item[0];
echo $positions->Lat[2];
echo $positions->Lon[2];

我没有错误,但我也没有在html页面中回复我的div。

目标

最终我想将JSON解码为PHP数组,这将有助于我更轻松地进行计算。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

无法使用

的常规方法传入字符串
xmlhttp.open("GET","Conversion_JQ.php?json=" + json, true);      

然而,像这样编码变量:

var uri = encodeRUIComponent(json);
xmlhttp.open("GET","Conversion_JQ.php?json=" + uri, true);  

允许变量传入。它最终有斜杠,所以我不得不使用

stripslashes($json);

在PHP端清理字符串。