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