原生js 以ajax(post)的方式传json至php,并让php解析为数组

时间:2020-09-15 21:02:07   收藏:0   阅读:40

如题。

比如要把一个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

之后在浏览器控制台中将会看到输出的数组。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!