获取服务器数据JSON.parse()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>获取服务器数据JSON.parse()</title> </head> <body> <button>获取服务器数据</button> <h3></h3> <script> var btn=document.getElementsByTagName('button').item(0); var request=new XMLHttpRequest(); btn.addEventListener('click',getData,false); function getData() { request.addEventListener('readystatechange',show,false); request.open('get','admin/demo1.php',true); request.send(null); } function show() { if(request.readyState===4){ var h3=document.getElementsByTagName('h3').item(0); var obj=JSON.parse(request.responseText); console.log(obj); h3.innerHTML=obj.name+'单价:'+obj.price+'数量:'+obj.count+'特征:'+obj.feature.color+'朋友:'+obj.friend[2]; h3.style.color='red'; } } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
<?php $json='{ "name":"小苹果", "id":110, "price":"8元", "count":"10斤", "feature":{ "color":"red", "size":"big" }, "friend":["梨","桃","香蕉","西瓜","橘子"] }'; echo $json;
点击 "运行实例" 按钮查看在线实例