javascript

原生js实现ajax。创建xhr对象


var xmlHttp;
function createxmlHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
}

 

get方法:


function doGet(url){
// 注意在传参数值的时候最好使用encodeURI处理一下,以防出现乱码
createxmlHttpRequest();
xmlHttp.open("GET",url);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
alert('success');
} else {
alert('fail');
}
}
}

post方法:


function doPost(url,data){
// 注意在传参数值的时候最好使用encodeURI处理一下,以防出现乱码
createxmlHttpRequest();
xmlHttp.open("POST",url);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(data);
xmlHttp.onreadystatechange = function() {
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
alert('success');
} else {
alert('fail');
}
}
}

posted @ 2015-07-11 11:07  coolkidboy  阅读(150)  评论(0编辑  收藏  举报