hybxiaodao 发表于 2013-1-23 01:22:00

ajax记录log

首先初始化ajaxhttp_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();//初始化ajaxvar 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();//初始化ajaxvar 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");
 
页: [1]
查看完整版本: ajax记录log