请求json数据

原生    //1创建异步调用             var request = new XMLHttpRequest();

 

            //2设置请求地址 参数             request.open("get", "./01data.json");

 

            //3设置响应http请求发生变化的函数             request.onreadystatechange = function () {

 

                if (request.status === 200 && request.readyState === 4) {

 

                    //5获取异步调用 返回数据                     var data = JSON.parse(request.responseText); //转换为json对象                     console.log(data);

 

                    //6使用 javaScript 和 DOM 实现局部刷新                     if(data.status===200){                         var cls=data.data;                         document.querySelector("h1").innerText=cls.name; //查找h1标签                     }else{                         console.log(data.msg)                     }                 }

 

            }             //4发送http请求             request.send(); 请求数据    $(function () {             $.ajax({
                type: "get", //请求方法                 url: "./01data.json", //地址
                data: { id: 10001 },//请求参数                 //data: "id=10001&name=张三",                 contentType: "json",//请求参数格式                 dataType: "json",//返回数据格式
                success: function (data) { //成功数据返回data                     console.log(data);                     if (data.status === 200) {                         var cls = data.data;                         $("legend").text(cls.name);
                        var students = cls.student;                         for (let i = 0; i < students.length; i++) {                             const stu = students[i];                             $(".data tbody").append("<tr><td>" + stu.id + "</td><td>" + stu.name + "</td></tr>");                         }
                    } else {                         console.log(msg);                     }                 },                 error: function (res, err) {//失败                     console.log(res); //详细错误                     //console.log(err);//错误返回err                 }
            })
            //简写             //URL [data] success [dataType]             $.get("./01data.json", function (data) {                 if (data.status === 200) {                     var cls = data.data;                     $("legend").text(cls.name);
                    var students = cls.student;                     for (let i = 0; i < students.length; i++) {                         const stu = students[i];                         $(".data tbody").append("<tr><td>" + stu.id + "</td><td>" + stu.name + "</td></tr>");                         //找到data类名内的tbody标签                     }
                } else {                     console.log(msg);                 }
            })         })     <body>     <legend></legend>     <table class="data">
        <thead>             <th>id</th>             <th>name</th>         </thead>
        <tbody>             <tr></tr>         </tbody>     </table> </body>

 

上一篇:单例设计模式的理解和分析


下一篇:Django(58)viewsets视图集详解