Last active
August 29, 2015 14:03
-
-
Save keenwon/1bc4e332977e619e056e to your computer and use it in GitHub Desktop.
原生Javascrip发送跨域ajax请求
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用时要后端设置: