原生ajax请求和jsonp

1.原生ajax请求

var obj = new XMLHttpRequest();
obj.open("POST", url, true);
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 发送信息至服务器时内容编码类型
obj.onreadystatechange = function () {
 if (obj.readyState == 4 && (obj.status == 200 || obj.status == 304)) { // readyState==4说明请求已完成
 console.log(obj.responseText);
}
else console.log("fail")
};
obj.send(data);
}

2.JSONP的核心是动态添加script标签来调用服务器提供的js脚本

function jsonp(options) {
        options = options || {};
        if (!options.url || !options.callback) {
            throw new Error("参数不合法");
        }

        //创建 script 标签并加入到页面中
        var callbackName = ('jsonp_' + Math.random()).replace(".", "");
        var oHead = document.getElementsByTagName('head')[0];
        options.data[options.callback] = callbackName;
        var params = formatParams(options.data);
        var oS = document.createElement('script');
        oHead.appendChild(oS);

        //创建jsonp回调函数
        window[callbackName] = function (json) {
            oHead.removeChild(oS);
            clearTimeout(oS.timer);
            window[callbackName] = null;
            options.success && options.success(json);
        };

        //发送请求
        oS.src = options.url + '?' + params;

        //超时处理
        if (options.time) {
            oS.timer = setTimeout(function () {
                window[callbackName] = null;
                oHead.removeChild(oS);
                options.fail && options.fail({ message: "超时" });
            }, time);
        }
    };

    //格式化参数
    function formatParams(data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[i]));
        }
        return arr.join('&');
    }

ajax与jsonp本质上不是一个东西,ajax的核心是通过XMLHttpRequest对象来获取非本页的内容,而jsonp则是通过动态创建script标签来获取服务器端的js脚本。

ajax与jsonp的本质区别不在于是否跨域,ajax通过服务器端代理(浏览器请求同源服务器,再由后者请求外部服务)也一样可以实现跨域,jsonp本身也可以获取同源的数据。

同源策略

javascript只能访问与包含他的文档在同一页面下的内容。

即主机名、协议、端口相同。

//下表给出了相对http://store.company.com/dir/page.html同源检测的示例:
//URL    结果    原因
http://store.company.com/dir2/other.html           成功     
http://store.company.com/dir/inner/another.html    成功     
https://store.company.com/secure.html              失败    协议不同
http://store.company.com:81/dir/etc.html           失败    端口不同
http://news.company.com/dir/other.html             失败    主机名不同
原文地址:https://www.cnblogs.com/cosyer/p/6618364.html