原生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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM