在標准瀏覽器下,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
