日期:2014-05-16  浏览次数:20867 次

AJAX技术之基本的封装 - Web 开发 / Ajax
ajaxDemo.js[b][/b]Ajax =  
function(){ 
  function request(url,opt){ 
  function fn(){} 
  var async = opt.async !== false, 
  method = opt.method || 'GET', 
  encode = opt.encode || 'UTF-8', 
  data = opt.data || null, 
  success = opt.success || fn, 
  failure = opt.failure || fn; 
  method = method.toUpperCase();  
  if(data && typeof data == 'object'){//瀵硅薄杞崲鎴愬瓧绗︿覆閿?煎 
  data = _serialize(data); 
  } 
  if(method == 'GET' && data){ 
  url += (url.indexOf('?') == -1 ? '?' : '&') + data; 
  data = null; 
  } 
  var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); 
  xhr.onreadystatechange = function(){ 
  _onStateChange(xhr,success,failure); 
  }; 
  xhr.open(method,url,async); 
  if(method == 'POST'){ 
  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=' + encode); 
  } 
  xhr.send(data); 
  return xhr; 
  } 
  function _serialize(obj){ 
  var a = []; 
  for(var k in obj){ 
  var val = obj[k]; 
  if(val.constructor == Array){ 
  for(var i=0,len=val.length;i<len;i++){ 
  a.push(k + '=' + encodeURIComponent(val[i])); 
  } 
  }else{ 
  a.push(k + '=' + encodeURIComponent(val)); 
  } 
  } 
  return a.join('&'); 
  } 
  function _onStateChange(xhr,success,failure){ 
  if(xhr.readyState == 4){ 
  var s = xhr.status; 
  if(s>= 200 && s < 300){ 
  success(xhr); 
  }else{ 
  failure(xhr); 
  } 
  }else{} 
  } 
  return {request:request}; 
}(); 
jsp页面
 <script type="text/javascript" src="<%=basePath%>ajaxDemo.js"></script>
 <script type="text/javascript">
function ajaxInsertReadState(){
var result = Ajax.request('servlet/ajaxDemo',{ 
  data : 'name=jack&age=20', 
  success : function(xhr){ 
  //to do with xhr 
  alert(xhr.responseText);
  }, 
  failure : function(xhr){ 
  //to do with xhr 
  alert("=====");
  } 
  } 
); 

}
</script>

------解决方案--------------------
什么问题。。