日期:2014-05-16 浏览次数:20639 次
首先初始化ajax
http_request = false;
function initAjax(){
//开始初始化XMLHttpRequest对象
if(window.XMLHttpRequest) { //Mozilla 浏览器
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {//设置MiME类别
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE浏览器
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) { // 异常,创建对象实例失败
window.alert("不能创建XMLHttpRequest对象实例.");
return false;
}
}
比如需要记录某个日志了,在js中可以这样写到:
//get请求
function log(){
initAjax();//初始化ajax
var url = "log.do?type=1"; //请求的url地址
http_request.open("get", url, true); //post请求,true表示异步请求,false表示同步,一般要用异步
http_request.send(null)//send(String s ) post请求才能设置s的值 get请求就直接null
}
//post请求
function log(){
initAjax();//初始化ajax
var url = "log.do"; //请求的url地址
http_request.open("post", url, true); //post请求,true表示异步请求,false表示同步,一般要用异步
para="id="+id+"&dateStr="+dateStr+"&userName="+userName;
para=encodeURI(para);
http_request.setRequestHeader("content-length",para.length);
http_request.SetRequestHeader("content-type","application/x-www-form-urlencoded");
http_request.send(para)//send(String s ) post请求才能设置s的值 get请求就直接null
}
?这要就异步请求到后台做处理了。
?
ajax请求结束后,会返回一个responseText
接上面的代码 在同一个方法里。
if (http_request.readyState == 4) { // 判断对象状态
if (http_request.status == 200) { // 信息已经成功返回,开始处理信息
if(http_request.responseText==null || http_request.responseText=="") return;
alert(http_request.responseText);
// 做相应处理
}else{
alert("获取信息失败");
}
}
?
补充说明:
encodeURI() 函数可把字符串作为 URI 进行编码。
decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码
?
发送请求的时候,向请求添加 HTTP 头
http_request.setRequestHeader("content-length",para.length);
http_request.SetRequestHeader("content-type","application/x-www-form-urlencoded");
?