JSON和Ajax

一、json序列化和解析

    <script>
        var person = {
            name: "tf",
            age: 22,
            body: {
                height: 172,
                weight: 60
            }
        }
        var personJson = JSON.stringify(person);
        console.log(personJson);
        var personJson2 = JSON.stringify(person, function (key, value) {
            switch(key){
                case "height":
                    return value + "cm";
                case "weight":
                    return value + "kg";
                default:  // 必须要有
                    return value;
            }
        })
        console.log(personJson2);
        var personJson3 = JSON.stringify(person, ["name", "age"], 4);
        console.log(personJson3);

        var personObj = JSON.parse(personJson2);
        console.log(personObj);
    </script>

二、Ajax请求

    <script>
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4){
                if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
//                    console.log(xhr.responseText);
                }else {
                    console.log("err " + xhr.status);
                }
                xhr = null;
            }
        }
        xhr.open("get", "data.json", true);
        xhr.send(null);

        var xhr2 = new XMLHttpRequest();
        xhr2.onreadystatechange = function () {
            if(xhr2.readyState == 4){
                if(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status == 304){
                    console.log(xhr2.responseText);
                }else {
                    console.log("err " + xhr2.status);
                }
                xhr2 = null;
            }
        }
        xhr2.onloadstart = function () {
            console.log("receive the first byte.");
        }
        xhr2.onprogress = function () {
            console.log("receiving the data.");
        }
        xhr2.onload = function () {
            console.log("receive all data.");
        }
        xhr2.onloadend = function () {
            console.log("complete!")
        }
        var myData = {
            "name": "zs"
        }
        var data = new FormData(myData);
        xhr2.open("post", "data.json");
        xhr2.send(data);
    </script>

三、jsonp跨域

    <script>
        var scr = document.createElement("script");

        scr.src = "https://suggest.taobao.com/sug?code=utf-8&q=%E5%8D%AB%E8%A1%A3&callback=cb";
        document.body.insertBefore(scr, document.body.firstChild);

        function cb(response) {
            console.log(response);
        }
    </script>

即通过script标签的src进行跨域访问接口,src参数包含一个回调函数(上为cb),接受参数为响应体。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值