前端代码
<!DOCTYPE html><html lang=‘en‘><head><meta charset=‘UTF-8‘><title>Title</title></head><body> ???</body></html><script src=‘jquery-3.2.1.js‘></script><script>$(function () { ???// 创建请求对象 ???var xhr = new XMLHttpRequest(); ???// 请求行 ???xhr.open("get", "data.php"); ???// 请求头 ???// 请求体 ???xhr.send(null); ???// 回调函数 ???xhr.onload = function() { ???????// 输出请求回来的数据 ???????console.log(xhr.responseText); ???????// 解析JSON数据 ???????var arr = JSON.parse(xhr.responseText); ???????// 如果JSON是数组, 则遍历输出 ???????for (let index = 0; index < arr.length; index++) { ???????????var element = arr[index]; ???????????console.log(element.name + "--" + element.gender); ???????} ???};});</script>
后端代码
<?php ???// 从文件获取JSON数据 ???$json = file_get_contents("data.json"); ???// 返回JSON数据 ???echo $json;?>
JSON代码
[ ???{"name":"Ray", "gender":"male"}, ???{"name":"Lee", "gender":"female"}, ???{"name":"Zero", "gender":"male"}]
<Ajax> 六. JSON数据解析
原文地址:https://www.cnblogs.com/ZeroHour/p/8350766.html