码迷,mamicode.com
首页 > Web开发 > 详细

新版XMLHttpRequest支持跨域请求

时间:2015-08-29 12:34:16      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

在标准浏览器下,XMLHttpRequest对象得到升级,支持跨域,用法不变,如下:

var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    alert(xhr.responseText);
                }
            }
        }
        xhr.open(‘get‘, ‘http://www.b.com/ajax.php‘, true);
        xhr.send();

但是在新版的XMLHttpRequest中并不推荐使用onreadystatechange事件,而推荐使用onload事件。

当然要想实现跨域,还需要在后端设置允许访问的域,例如:

header(‘Access-Control-Allow-Origin:http://www.a.com‘);

不过在IE下以上都是白说了,IE下使用XDomainRequest对象来实现跨域请求。

用法如下:

ar oXDomainRequest = new XDomainRequest();
        oXDomainRequest.onload = function() {
            alert(this.responseText);
        }
        oXDomainRequest.open(‘get‘, ‘http://www.b.com/ajax.php‘, true);
        oXDomainRequest.send();

XMLHttpRequest2参考网址:http://www.w3.org/TR/XMLHttpRequest2/

XDomainRequest参考网址:https://msdn.microsoft.com/en-us/library/cc288060(VS.85).aspx

新版XMLHttpRequest支持跨域请求

标签:

原文地址:http://www.cnblogs.com/toodeep/p/4768811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!