zoukankan      html  css  js  c++  java
  • <Ajax> 六. JSON数据解析

    前端代码

    <!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"}
    ]
  • 相关阅读:
    第六周
    第五周(实验报告)
    第四周(实验报告)
    第三周(实验报告)
    Java第二周学习总结
    第一周
    2019课程总结
    第十四周课程总结
    第十三周总结
    第十二周总结
  • 原文地址:https://www.cnblogs.com/ZeroHour/p/8350766.html
Copyright © 2011-2022 走看看