var net = new Object();
net.ajaxRequest = function(url, onload, onerror, method, params){
//XMLHttpRequest对象
this.req = null;
this.onload = onload;
//错误操作
this.onerror = (onerror) ? onerror : this.defaultError;
//ajax所有操作
this.loadDate(url, method, params);
}
net.ajaxRequest.prototype.loadDate = function (url, method, params){
if(method){
method = “POST”;
}
if(window.XMLHttpRequest){
this.req = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
http_requestHav = false;
}
}
}
if(this.req){
try{
var loader = this;
this.req.onreadystatechange = function(){
net.ajaxRequest.onReadyState.call(loader);
//alert(loader + this);
}
this.req.open(method, url, true);
if(method == "POST"){
this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
this.req.send(params);
}catch(err){
this.onerror.call(this);
}
}else{
alert("XMLHttpRequest对象获取失败");
}
}
//重构函数
net.ajaxRequest.onReadyState = function(){
var req = this.req;
var ready = req.readyState;
if(ready == 4){
if(req.status == 200){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
}
//默认错误处理函数
net.ajaxRequest.prototype.defaultError = function(){
alert(“数据错误\n回调状态:”+this.req.readyState +”\n状态:”+this.req .status);
}
1.重构的代码哪都能下载;
2.js新建对象 new Object();
3.post请求需要this.req.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);否则request.getParameter()获取不到请求参数。
4.get请求:请求路径?参数名=参数值&参数名=参数值
5.Post请求:请求路径后不跟参数值,ajax重构在params中添加参数
new net.ajaxRequest(“../GetPronvince”,deal_getProvince,null,”POST”,”action=getProvince&nocache=” + new Date().getTime());
6.document.getElementById(“province”).onchange = function(){getCity(document.getElementById(“province”).value);:onchange调用js方法
7.路径问题:同一文件夹下可直接写文件名+后缀。不在同一文件夹可用”../”返回上级目录,返回到根目录再按文件在项目的路径找到文件。
8.一定要注意contenttype的值,和参数的编码格式。