javascript与php直接的json交互

JS变量存储json值,代码如下:

var g_map_json = '{"mainElements":["main_1","main_2"],"tipElements":["tip_1"],"subElements":["sub-1"]}';

var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        //document.getElementById("writeFictionArea").innerHTML=xmlhttp.responseText;
        g_map_json = xmlhttp.responseText;
        //g_map_json = JSON.stringify(xmlhttp.responseText);
        console.log("-->  (3) g_map_json:");
        console.log(g_map_json);
    }
}
xmlhttp.open("POST","/super_writer_api/save_map",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("mapJson="+mapJson);

php代码将json数据保存,并返回json。数据本身不做任何改变。

if (isset($_POST['mapJson'])) {
    $this->info->tag = $_POST['mapJson'];
    file_put_contents($this->dataFile, $this->info->tag);
}
echo $this->info->tag;

查看控制台输出,可知发送的json数据与返回的json数据相同,实际测试发现数据也是可用的。
验证成功。
这里写图片描述

本文的意义在于打通php与js之间的json传输通路。

解决问题-1:
Uncaught TypeError: Cannot read property '1' of undefined...
解决问题-2:
Uncaught SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse

猜你喜欢

转载自blog.csdn.net/dreamstone_xiaoqw/article/details/80310849