通过我的工作网络时,以下代码适用于 IE9 和跨域 json 调用。通过我的 3G 调制解调器尝试相同的代码时,我得到一个错误访问被拒绝。它适用于chrome和firefox。只有 IE9 给予访问被拒绝。请协助...
if (!jQuery.support.cors && window.XDomainRequest) {
//alert("in cors");
var httpRegEx = /^http?:\/\//i;
var getOrPostRegEx = /^get|post$/i;
var sameSchemeRegEx = new RegExp('^'+location.protocol, 'i');
var xmlRegEx = /\/xml/i;
// ajaxTransport exists in jQuery 1.5+
jQuery.ajaxTransport('text html xml json', function(options, jqXHR){
// XDomainRequests must be: asynchronous, GET or POST methods, HTTP or HTTPS protocol, and same scheme as calling page
if (params.crossDomain && params.async && getOrPostRegEx.test(params.type) && httpRegEx.test(options.url) && sameSchemeRegEx.test(options.url)) {
var xdr = null;
var userType = (options.dataType||'').toLowerCase();
return {
send: function(headers, complete){
xdr = new XDomainRequest();
if (/^\d+$/.test(options.timeout)) {
xdr.timeout = options.timeout;
}
xdr.ontimeout = function(){
complete(500, 'timeout');
};
xdr.onload = function(){
alert("OnLoad");
var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
var status = {
code: 200,
message: 'success'
};
var responses = {
text: xdr.responseText
};
try {
if (userType === 'json') {
try {
responses.json = JSON.parse(xdr.responseText);
} catch(e) {
status.code = 500;
status.message = 'parseerror';
//throw 'Invalid JSON: ' + xdr.responseText;
}
} else if ((userType === 'xml') || ((userType !== 'text') && xmlRegEx.test(xdr.contentType))) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = false;
try {
doc.loadXML(xdr.responseText);
} catch(e) {
doc = undefined;
}
if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
status.code = 500;
status.message = 'parseerror';
throw 'Invalid XML: ' + xdr.responseText;
}
responses.xml = doc;
}
} catch(parseMessage) {
throw parseMessage;
} finally {
//alert(status.code);
complete(status.code, status.message, responses, allResponseHeaders);
}
};
xdr.onerror = function(){
complete(500, 'error', {
text: xdr.responseText
});
};
xdr.open(params.type, params.url);
//xdr.send(options.data);
xdr.send();
//params.success(result, textStatus, jqXHR);
},
abort: function(){
if (xdr) {
xdr.abort();
}
}
};
}
});
};
jQuery.support.cors = true;
//****************//
$.ajax({
url: params.url,
type: params.type,
dataType: params.dataType,
//contentType: "application/json;charset=utf-8",
async: params.async,
cache:params.cache,
data:params.data,
success: function(result, textStatus, jqXHR){
result=result.replace(/(\r\n|\n|\r|\\)/gm,"");
//console.log(result);
params.success(result, textStatus, jqXHR);
},
contentType:params.contentType,
error: function(xhrSend, textStatus, errorThrown){
if(times>0){
makeRequest(times,params);
}else{
//alert(params.url+params.data);
//alert(xhrSend);
//alert(textStatus);
//alert(errorThrown);
params.error(xhrSend, textStatus, errorThrown);
}
}
});