<?php header("content-type:text/html;charset=utf-8"); echo '{"name":"小明","age":"12","sex":"男"}'; ?>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button id="bt1">點擊獲取json數據</button> <script type="text/javascript"> window.onload=function(){ var bt1=document.getElementById("bt1"); bt1.onclick=function(){ //建立ajax對象,寫兼容 if(window.XMLHttpRequest){ var xhr=new XMLHttpRequest(); }else{ var xhr=new ActiveXObject("Microsoft.XMLHTTP"); }; //設置發送數據的地址和方法 xhr.open("POST","json.php"); //設置咱們的請求頭信息,post方法才寫請求頭 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //發送數據 xhr.send(); //綁定onreadystatechange事件 xhr.onreadystatechange=function(){ if(xhr.readyState==4 && xhr.status==200){ var data=xhr.responseText; //json字符串轉換成爲json對象 , data=eval("("+data+")");evel不存在兼容性問題,可是會有安全漏洞。 data=JSON.parse(data); var str=""; str+="姓名:"+data.name+"<br>"; str+="年齡:"+data.age+"<br>"; str+="性別:"+data.sex; document.body.innerHTML=str; }; }; }; }; </script> </body> </html>