在标准浏览器下,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

posted on 2015-08-29 11:34  toodeep  阅读(5288)  评论(0编辑  收藏  举报