当前位置: 代码迷 >> Ajax >> AJAX接口及普普通通AJAX使用及示例
  详细解决方案

AJAX接口及普普通通AJAX使用及示例

热度:830   发布时间:2012-11-23 00:03:43.0
AJAX接口及普通AJAX使用及示例
以下为示例:
1:AJAX接口
var Ajax=function(){
  var request=new ActiveXObject("Msxml2.XMLHTTP");
  var remoteURL;
  var sync=false;
  var requestParameter=new Object();
  var cache=false;
  //设置cache
  this.setCache=function(flag){
    cache=flag;
  };
  this.isSync=function(){
    sync=true;
  };
  /**
   * 远程请求AJAX 地址
  */
  this.setRemoteURL=function(url){
    remoteURL=url;
  };
  //获取url地址
  var getCacheParameterString=function(){
    if(!cache){
      return "&random="+Math.random();
  }
return '';
};
  /**
   * 设置的请求参数
  */
  this.setParameter=function(key,value){
    requestParameter[key]=value;
  };
  /**
   * 获取请求参数,local函数
  */
  var getParameterString=function(){
    var parameterString="";
    for(var key in requestParameter){
      var value=requestParameter[key];
      parameterString=parameterString+"&"+key+"="+value;
    }
    //如果存在参数
    if(parameterString!=""){
      parameterString="?"+parameterString.substring(1);
    }
    return parameterString;
  };
  /**
   * 处理请求
  */
  this.sendGetRequest=function(){
    //获取请求参数
    request.open("get",remoteURL+getParameterString()+getCacheParameterString(),!sync);
    //状态改变
    var self=this;
    //回调函数
    request.onreadystatechange=function(){
    if (request.readyState == 1){
    self.onLoading();
  }
    if(request.readyState == 4){
    if(request.status==200){
    self.onSuccess();
    }else{
    self.onError();
    }
    }
  };
request.send("");
  };
   
  this.sendPostRequest=function(){
    //获取请求参数
    request.open("post",remoteURL,!sync);
    ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //状态改变
    var self=this;
    //回调函数
    request.onreadystatechange=function(){
  if (request.readyState == 1){
  self.onLoading();
  }
  if(request.readyState == 4){
  if(request.status==200){
  self.onSuccess();
  }else{
  self.onError();
  }
  }
  };
 
request.send(getParameterString());
  };
   
  //获取返回TEXT
  this.getResponseText=function(){
    return request.responseText;
  }
  //获取返回HTML
  this.getResponseXML=function(){
    return request.responseXML;
  }
  /**
   * 正在处理操作
  */
  this.onLoading=function(){
    alert("数据获取中");
  };
  //成功操作
  this.onSuccess=function(){
    alert("返回成功");
  };
  //如果失败
  this.onError=function(){
    alert("失败");
  };
}

function queryPolicyListByInfo(){
var policyNo = document.form_A.policyNo.value;
var certificateNo = document.form_A.certificateNo.value;
var insurantName = document.form_A.insurantName.value;
var partyNo = document.form_A.partyNo.value;
var page = document.form_A.page.value;
var pageSize = document.form_A.pageSize.value;
var ajax = new Ajax();
ajax.onLoading=function(){
    document.getElementById("resultDiv").innerText="你到底是出来了啊!";
  };
  ajax.onError=function(){
    document.getElementById("resultDiv").innerText="你到底是出来啊";
  };
ajax.onSuccess=function(){
var result = ajax.getResponseText();
document.getElementById("resultDiv").innerText=result;
}
ajax.setRemoteURL("common/queryPolicyList.do");
  ajax.setParameter("policyNo",policyNo);  
  ajax.setParameter("certificateNo",certificateNo);
  ajax.setParameter("insurantName",insurantName);
  ajax.setParameter("partyNo",partyNo);  
  ajax.setParameter("page",page);
  ajax.setParameter("pageSize",pageSize);
  ajax.sendGetRequest();
}

protected ModelAndView handleRequestInternal
(HttpServletRequest request, HttpServletResponse response) {
try {
    if (request.getMethod().equals("GET"))
request.setCharacterEncoding("UTF-8");
    response.setContentType("text/xml; charset=GBK");
    response.setDateHeader("Expires", 0L);
    PrintWriter out = response.getWriter();
    XMLOutputter outputter = new XMLOutputter();
    AJAXXMLDocument icssdoc = new AJAXXMLDocument();
    AJAXRequest aRequest = new AJAXRequest(request, response);
    AJAXResponse result = new AJAXResponse();
    result = handleRequest(aRequest);
    if (result != null) {
icssdoc.setReturnFlag(String.valueOf(result.getReturnFlag()));
icssdoc.setReturnMessage(result.getReturnMsg());
Iterator it = result.keySet().iterator();
while (it.hasNext()) {
    String key = (String) it.next();
    icssdoc.addObject(key, result.get(key));
}
    } else {
icssdoc.setReturnFlag("-1");
icssdoc
    .setReturnMessage("\u8fd4\u56de\u7ed3\u679c\u4e3a\u7a7a");
    }
    outputter.setEncoding("GBK");
    outputter.output(icssdoc.getICSsXMLDocument(), out);
    out.flush();
    out.close();
} catch (Exception e) {
    logger.error(e.getMessage(), e);
    response.setContentType("text/xml; charset=GBK");
    response.setDateHeader("Expires", 0L);
    XMLOutputter outputter = new XMLOutputter();
    AJAXXMLDocument icssdoc = new AJAXXMLDocument();
    icssdoc.setReturnFlag("-1");
    icssdoc.setReturnMessage
("\u7cfb\u7edf\u5185\u90e8\u9519\u8bef\uff1a"
+ e.getMessage());
    try {
PrintWriter out = response.getWriter();
outputter.setEncoding("GBK");
outputter.output(icssdoc.getICSsXMLDocument(), out);
out.flush();
out.close();
    } catch (IOException e1) {
logger.error(e.getMessage(), e);
    }
}
return null;
    }

2:普通AJAX使用示例
var XMLHttpReq;                                                                  
   function createXMLHttpRequest() {                                                
     if (window.XMLHttpRequest) {                                                 
        XMLHttpReq = new XMLHttpRequest();                                       
     }                                                                            
     else if (window.ActiveXObject) {                                             
        try {                                                                    
            XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");                    
        } catch (e) {                                                            
            try {                                                                
                XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");             
            } catch (e) {                                                        
            }                                                                    
        }                                                                        
    }                                                                            
}                                                                                
                                                                                 
function changeValue(departmentCode) {
    alert(departmentCode);                                                      
    createXMLHttpRequest();                                                      
    if(departmentCode=="")                                                                  
    {                                                                            
    alert("请选择机构码!");return;                                                
    }                                                                            
    var url="<c:url value="/commonset/departmentAccount/searchTaxNoByDepartmentCode.do"/>"+"?departmentCode="+departmentCode;                                                   
    XMLHttpReq.open("GET", url, true);                                        
    XMLHttpReq.onreadystatechange = updateText;                                  
    XMLHttpReq.send(null);                                                      
}                                                                                
                                                                                 
function updateText() {                                                          
if (XMLHttpReq.readyState == 4) {                                              
      if (XMLHttpReq.status == 200) {                                                
        var res = XMLHttpReq.responseText;
        alert(res);                              
        document.getElementById("taxno").value=res;                                     
      } //else {                                                                         
        //alert('你所请求的页面有问题');                                                   
      //}                                                                                
   }                                                                                
}                   

protected ModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response) throws Exception{
//第一步 创建ServiceRequest
Map map = new HashMap();
String departmentCode = request.getParameter("departmentCode");
System.out.println("haha");
System.out.println(departmentCode);

map.put("departmentCode", departmentCode);

ServiceRequest serviceRequest = new ServiceRequest();
//ID必须在biz-context.xml中定义
serviceRequest.setRequestedServiceID(BizContextNames.SEARCH_TAX_INFO_ACTION);
serviceRequest.setCurrentRequestObject(map);

//第2步 dispatchService()将请求转发到业务层
ServiceResponse serviceResponse = dispatchService(serviceRequest,WebContextNames.PAFA_AC);

//第3步 返回数据模型和视图供前台显示
Map model = serviceResponse.getModel();
System.out.println(model);
String taxRegisterNo="";
if(model.containsKey("searchTaxNoResult")){
taxRegisterNo = (String) model.get("searchTaxNoResult");
}
System.out.println("qqqqq");
System.out.println("11111111"+taxRegisterNo);
//List resultList = (List) model.get(ServiceResponse.SERVICE_RESPONSE_RESULT);
/*DepartmentAccountDTO departmentAccountDTO=null;
String taxRegisterNo="";
if(resultList.size()>0)
{
  departmentAccountDTO=(DepartmentAccountDTO)resultList.get(0);
  taxRegisterNo=(String)departmentAccountDTO.getTaxRegisterNo();
} */

//response.setCharacterEncoding("GBK");


response.setHeader("Charset", "GBK");         
//response.setCharacterEncoding("GBK");

response.setContentType("text/xml");          
PrintWriter writer = response.getWriter();    
writer.write(taxRegisterNo);                
writer.flush();                           
return null;

}
  相关解决方案