原生js實現ajax跨域(兼容IE8,IE9)


html設置meta標簽兼容360兼容模式和IE怪異模式

<meta http-equiv="X-UA-Compatible" content="IE=9;IE=8;IE=7;ie=edge">

原生js跨域

var xhr = null; // IE8/9需用window.XDomainRequest兼容
if (window.XDomainRequest) {
    xhr = new XDomainRequest();
    xhr.onload = function () {
        console.log(xhr.responseText);
    }
    xhr.open("get", 'http://test.aa.com');
    xhr.send();
} else {
    xhr = new XMLHttpRequest();
    // 前端設置是否帶cookie
    xhr.withCredentials = true;
    xhr.open('post', 'http://test.aa.com', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send('user=admin');

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(JSON.parse(xhr.responseText).name);
        }
    };
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM