美文网首页
原生AJAX获取mock数据

原生AJAX获取mock数据

作者: Hello杨先生 | 来源:发表于2019-07-20 23:53 被阅读0次
    {
      "code": 1,
      "data": {
        "goods": [
          {
            "id": 1001,
            "name": "食物1",
            "code": 19971001,
            "kind": "零食"
          },
          {
            "id": 1002,
            "name": "食物2",
            "code": 19971002,
            "kind": "零食"
          },
          {
            "id": 1003,
            "name": "食物3",
            "code": 19971003,
            "kind": "零食"
          },
          {
            "id": 1004,
            "name": "食物4",
            "code": 19971004,
            "kind": "零食"
          }
        ]
      }
    }
    
    <script>
    
        var url = "https://www.easy-mock.com/mock/5d257e0d77744b2808b8840d/study/goods";
        var btn = document.getElementsByTagName("button")[0]
        var tbody = document.getElementById("tbody")
        var response;
        var str = ""
    
        // tbody.innerHTML="nihao"
    
        btn.addEventListener("click", function () {
    
            var myAjax = new XMLHttpRequest();
            myAjax.open("get", url, true);
    
            myAjax.onreadystatechange = function (show) {
                if (myAjax.readyState == 4 && myAjax.status == 200) {
                    console.log(myAjax.response)
                    response = JSON.parse(myAjax.response)//将json字符串转换成json对象
                    // document.write(response.data.goods[1].name)
                    response.data.goods.forEach(function (item, i) {
                        str += `<tr><td>${item.id}</td><td>${item.name}</td><td>${item.code}</td><td>${item.kind}</td></tr>`
                    })
                    tbody.innerHTML = str
                } else {
                    alert("请求失败")
                    return "请求失败"
                }
            }
            myAjax.send()
    
            // var res = myAjax.onreadystatechange()
    
    
        })
    
    
    
    
    </script>
    
    
    image.png

    相关文章

      网友评论

          本文标题:原生AJAX获取mock数据

          本文链接:https://www.haomeiwen.com/subject/axbplctx.html