原生js 以ajax,post的方式传json至php,并让php解析为数组
如题。
比如要把一个json,如 json= {name:"John Rambo", time:"3pm"},,通过js ,传到一个php服务器 fwq.php中,并解析为数组。
方法如下。
js
//建立协议 xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)//接收后要做的事。
{
console.log(xmlhttp.responseText);
}
}
var json_obj = JSON.stringify({name:"John", time:"12:00"});
var json_upload = "You_name=" + json_obj;
xmlhttp.open("POST", "fwq.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
}
fwq.php
<?php $jsons= $_POST['You_name'];
//转化为数组
\(arr = json_decode(\)jsons,true);
//输出
var_dump($arr);
?>
然后运行js
之后在浏览器控制台中将会看到输出的数组。