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

每次用Ajax,都需要这么复杂吗?
我每次创建一个对象,都要这样复杂吗?

JScript code

"testAjax.htm" 文件:<html> 
  <body> 
  <script type="text/javascript"> 
  function ajaxFunction() 
  { 
  var xmlHttp; 
  try 
  { 
  // Firefox,Opera 8.0+,Safari 
  xmlHttp=new XMLHttpRequest(); 
  } 
  catch (e) 
  { 
  // Internet Explorer 
  try 
  { 
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
  } 
  catch (e) 
  { 
  try 
  { 
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
  } 
  catch (e) 
  { 
  alert("您的浏览器不支持AJAX!"); 
  return false; 
  } 
  } 
  } 
  } 
  </script> 
  <form name="myForm"> 
  用户: <input type="text" name="username" /> 
  时间: <input type="text" name="time" /> 
  </form></body> 
  </html> 





首先声明一个保存 XMLHttpRequest 对象的 xmlHttp 变量。 
  然后使用 XMLHttp=new XMLHttpRequest() 来创建此对象。这条语句针对 Firefox、Opera 以及 Safari 浏览器。假如失败,则尝试针对 Internet Explorer 6.0+ 的 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"),假如也不成功,则尝试针对 Internet Explorer 5.5+ 的 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")。 
  假如这三种方法都不起作用,那么这个用户所使用的浏览器已经太过时了,他或她会看到一个声明此浏览器不支持 AJAX 的提示。 


------解决方案--------------------
可以把这个函数的定义单独保存为一个js文件,在需要使用AJAX的页面中引用这个文件就可以了。
------解决方案--------------------
JScript code

function CreateHTTPObject()
{
    var xmlhttp;    
    try
    {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
        try
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
            xmlhttp = false;
        }
    }
    
    if (!xmlhttp && typeof XMLHttpRequest!='undefined')
    {
        try
        {
            xmlhttp = new XMLHttpRequest();
        }
        catch (e)
        {
            xmlhttp=false;
        }
    }
    
    if (!xmlhttp && window.createRequest)
    {
        try
        {
            xmlhttp = window.createRequest();
        }
        catch (e)
        {
            xmlhttp=false;
        }
    }
    
    return xmlhttp;
}

------解决方案--------------------
定义上面的函数,
调用时创建实例即可:
JScript code

var xmlHttp = CreateHTTPObject();
    if (!xmlHttp)
    {
        return; //无法创建 xmlhttp 对象
    }

xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = function(){HandleRequest(xmlHttp, "元素ID")};
    xmlHttp.send(null);

------解决方案--------------------
可以用jquery ,一句话搞定;
$(document).ready(function(){
$("#userpass").blur(function(){
var password=$("#userpass").val();
var name=$("#username").val();
if(password==""||password==null){
$("#pass").html("<font color='red'>请输入密码! </font>");
b=false;
}else if(!/^[a-zA-Z0-9_]{6,16}$/.test(password)){
$("#pass").html("<font color='red'>输入格式不正确!密码应至少6为数字或字符 </font>");
b=false;
}else{
$.get("LoginAjaxPassword",{"userpass":encodeURI(encodeURI(password)),"username":encodeURI(encodeURI(name))},function(response){
$("#pass").html(response);
if(response=="<font color='green' size='2' >"+"√"+"</font>"){
b=true;
}
});

}
return b;
}); 

$("#login-submit").click(function(){