Skip to content

Instantly share code, notes, and snippets.

@hacke2
Last active August 29, 2015 14:05
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 hacke2/2b784d448f01c3a1a4e3 to your computer and use it in GitHub Desktop.
Save hacke2/2b784d448f01c3a1a4e3 to your computer and use it in GitHub Desktop.
自己封装的JAJAX
function Ajax(parametObject) {
var xhr, responseType, defineParam, method, url, data;
defineParam = {
method : "GET",
type : "json"
}
url = parametObject.url;
data = parametObject.data;
responseType = parametObject.type || defineParam.type;
method = parametObject.method || defineParam.method;
if(navigator.userAgent.toUpperCase().indexOf('MSIE') >= 0){
try{
xhr=new ActiveXObject('microsoft.xmlhttp');
}catch(e){
//蜈シ螳ケIE5.5縲!E5
xhr=new ActiveXObject('msxml2.xmlhttp');
}
}else{
xhr=new XMLHttpRequest();
};
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(responseType == "json") {
responseType = xhr.responseText;
}else {
responseType = xhr.responseXML;
}
if(xhr.status== 200 && typeof(parametObject.success) == 'function') {
parametObject.success(responseType);
}else if(xhr.status != 200 && typeof(parametObject.error) == 'function') {
parametObject.error(responseType);
}
}
}
if(method.toUpperCase() == "GET") {
if(data) {
url = url + '?' + data + '&random=' +Math.random();
}
xhr.open('GET', url, true);
xhr.send(null);
}
if(method.toUpperCase() == "POST") {
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
}
}
Ajax({
url : "http://wenku.baidu.com/view/5e59b08a84868762caaed526.html",
error : function(data) {
alert(data);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment