Correction status:Uncorrected
Teacher's comments:
从服务器端获取JSON格式字符串并解决到前端页面中显示
下面是html代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模拟获取服务器数据</title> <style> button{ background-color: cornflowerblue; } button:hover{ color: orangered; } /*#h3-1{*/ /*display: none;*/ /*}*/ </style> </head> <body> <h3 >点击事件模拟获取服务器数据</h3> <button>点我获取数据</button> <h3 id="h3-1"></h3> <script> //获取button按钮 var btn = document.getElementsByTagName('button').item(0); //生成一个Ajax对象 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); } var h3 = document.getElementsByTagName('h3').item(1); function show() { // // if (h3.style.display === "none") { // h3.style.display = "block"; // } else { // h3.style.display = "none"; // } if (request.readyState === 4){ var obj = JSON.parse(request.responseText); console.log(obj); if (h3.style.display === "none") { h3.style.display = "block"; h3.innerHTML = obj.name + ',PHP成绩是: ' + obj.grade.php + ',最喜欢: ' + obj.hobby[1]; } else { h3.style.display = "none"; h3.innerHTML = ''; } } } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
php代码模拟服务器数据:
<?php $json = '{ "name": "小金莲", "age": 23, "isMarried": true, "sweetheart": null, "grade": { "javascript": 80, "php": 90 }, "hobby": ["做烧饼", "下毒", "饮酒作乐"] }'; echo $json;
点击 "运行实例" 按钮查看在线实例