Skip to content

Instantly share code, notes, and snippets.

@keenwon
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keenwon/1bc4e332977e619e056e to your computer and use it in GitHub Desktop.
Save keenwon/1bc4e332977e619e056e to your computer and use it in GitHub Desktop.
原生Javascrip发送跨域ajax请求
function ajax (options) {
var type = (options.type || 'GET').toLocaleLowerCase(),
url = options.url,
data = options.data,
dataType = (options.dataType || 'json').toLocaleLowerCase(),
success = options.success;
//IE10以下
if (window.XDomainRequest) {
// 创建ajax引擎对象
var xdr = null;
xdr = new window.XDomainRequest();
xdr.onload = function () {
if (dataType === 'text') {
success && success(xdr.responseText);
} else if (dataType === 'xml') {
success && success(xdr.responseXML);
} else if (dataType === 'json') {
success && success(eval('(' + xdr.responseText + ')'));
}
};
// 打开
xdr.open(type, url, true);
// 如果需要Cookie的话,只能当成参数传递
// 发送
if (type === 'get') {
xdr.send(null);
} else if (type === 'post') {
//XDomainRequest无法设置头信息,只支持text/plain,需要后端从流里面读取数据
xdr.send(this.objToQueryStr(data));
}
} else {
// 创建ajax引擎对象
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new window.XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (dataType === 'text') {
success && success(xhr.responseText);
} else if (dataType === 'xml') {
success && success(xhr.responseXML);
} else if (dataType === 'json') {
success && success(eval('(' + xhr.responseText + ')'));
}
}
};
// 打开
xhr.open(type, url, true);
// 支持Cookie,HTTP认证等
xhr.withCredentials = true;
// 发送
if (type === 'get') {
xhr.send(null);
} else if (type === 'post') {
//设置头信息
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(this.objToQueryStr(data));
}
}
}
@keenwon
Copy link
Author

keenwon commented Jul 11, 2014

使用时要后端设置:

response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST,GET");
response.addHeader("Access-Control-Allow-Credentials", "true");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment