ajax 输出json数据

顺口溜:

一个对象(var xhr=new XMLHttpRequest();)下有两个方法(xhr.open('get',url,true); xhr.send();)

两个方法中间夹着个事件(xhr.onreadystatechange=function(){})函数

函数里有个如果去验证(if(4==this.readyState && 200==this.status){})

最后还要去抉择哪一个属性(var txt=xhr.responseText;或xhr.responseText;)

基本流程如下

var xhr=new XMLHttpRequest();
        var url='caipu.json';
        xhr.open('get',url,true);
        xhr.onreadystatechange=function(){
            if(4==this.readyState && 200==this.status){
                var txt=xhr.responseText;
                }

            }
        }
        xhr.send();

实例 创建json文件,由于这家伙也是个对象,所以就采用名值对的方式进行,但由于是多个对象,所以就通过数组的【】将他们包(抱)起来!

{
    "menu":[
        {
        "name":"溜肉段1",
        "price":"10.00"
        },
        {
        "name":"段2",
        "price":"11.00"
        },
        {
        "name":"溜段3",
        "price":"15.00"
        },
        {
        "name":"溜肉4",
        "price":"12.00"
        },
        {
        "name":"溜肉段5",
        "price":"12.00"
        },
        {
        "name":"溜肉6",
        "price":"11.00"
        },
        {
        "name":"溜肉段7",
        "price":"10.00"
        },
        {
        "name":"溜肉段8",
        "price":"10.00"
        },
        {
        "name":"溜肉段9",
        "price":"10.00"
        }
    ]
}

用AJax输出文件,不过建的确实HTML文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>获取数据</title>
</head>
<body>
    <div class="data"></div>
    <script>
        var $=function(sel){
            return document.querySelector(sel);
        }
        var xhr=new XMLHttpRequest();
        var url='caipu.json';
        xhr.open('get',url,true);
        xhr.onreadystatechange=function(){
            if(4==this.readyState && 200==this.status){
                var txt=xhr.responseText;
                // var o=eval("("+txt+")");
                var o=JSON.parse(txt);
                //  console.log(o);
                // console.log(typeof txt);
                // document.write(o.menu.length);
                // document.write(o.menu[0].name);
                var cai=""
                for(var i=0;i<o.menu.length;i++){

                    cai+="菜名:"+o.menu[i].name+"<br />价格:"+o.menu[i].price+"<br>"+"<hr>";

                    $('.data').innerHTML+=cai;
                    // $('.data').innerHTML+="菜名:"+o.menu[i].name+"&nbsp;&nbsp;&nbsp;价格:"+o.menu[i].price+"<br>";
                }

            }
        }
        xhr.send();

        // $('.data').innerHTML+=
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/yinwangyizhi/p/9112820.html