ie8下js提交get請求遇到拒絕訪問的問題
阿新 • • 發佈:2019-01-22
Js用Ajax提交get請求時,在Ie8下遇到拒絕訪問的問題,有人說這是跨域引起的,可以設定Ie的安全性來避免這個問題,具體如下:
IE工具->internet選項->安全->自定義級別->通過域訪問資料來源,改成啟用,就可以傳送請求獲取資料了,不知道這對跨域的安全性有什麼影響沒,但在ff和chrome下是可以直接傳送和獲取資料的,具體如下:
var myText;
var text = "";
function request(url, params) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
readyStateChanged(xhr);
}
var result = url;
for (var i in params) {
result = addURLParam(result, i, params[i]);
}
console.log(result);
xhr.open("get", result, true);
xhr.send(null);
}
function readyStateChanged(xhr) {
console.log("xhr readyState: " + xhr.readyState);
console.log(xhr.responseText)
if(typeof myText == "undefined") {
myText = document.getElementById("myText");
}
console.log("status=" + xhr.status);
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || (xhr.status == 304)) {
//console.log(xhr.responseText);
text += xhr.responseText;
}
else {
console.log("Request was unsuccessfull: status=" + xhr.status + ", url=" + url);
text += "Request was unsuccessfull: status=" + xhr.status + ", url=" + url;
}
myText.innerHTML = text;
}
}
function addURLParam(url, name, value) {
url += (url.indexOf("?") == -1) ? "?" : "&";
url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
return url;
}
呼叫方法如下:
var params = new Object();
var url = "...";
params.type= 0;
params.id= 0;
request(url, params);
後來才發現,在ie下不能用XMLHttpRequest,而是要改用XDomainRequest類,修改如下:
function ieRequest(url, params) {
var xdr = new XDomainRequest();
xdr.onload = function() {
//readyStateChanged(xdr);
console.log(xdr.responseText);
}
var result = url;
for (var i in params) {
result = addURLParam(result, i, params[i]);
}
console.log(result);
xdr.open("get", result);
xdr.send(null);
}
修改後再將上面的通過域訪問資料來源改成禁止訪問,這樣就可以傳送和接受get請求了。
要吐血了,web前端真不是人乾的事情