JavaScript&&AJAX代码集萃

lgl669 2009-06-16
<script type="text/javascript">
//创建XMLHttp对象
  var xmlHttp;
//浏览器兼容
   function createXmlHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
alert("AJAX");
   }
         }


function createQueryString(){
var loginName = document.getElementById("loginName").value;
    var queryString = "loginName="+loginName;
    return queryString;
  }
 
function callBack(){
  if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var result=document.getElementById("serverResponse");
var rootNode=xmlHttp.responseXML.documentElement;
var node=rootNode.getElementsByTagName("info");
result.innerHTML=node[0].firstChild.nodeValue;
  }
  }
  }
  function sendPostRequest(){
createXmlHttpRequest();
var url = "validateName";
   queryString = createQueryString();
    xmlHttp.onreadystatechange = callBack;
   xmlHttp.open("post",url);
   xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");  
xmlHttp.send(queryString);
    }
  </script>
客户端html中对应代码:
<form action="#"><table>
<tr>
<td> </td>
<td><input type="text" id="loginName" name="loginName" onblur="sendPostRequest()"/></td>
    <td><div id="serverResponse"></div></td>
</tr>
在对应处理信息的servlet中代码:
public class ValidateName extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
System.out.println("**********in doGet()**********");
String loginName = request.getParameter("loginName");
System.out.println("loginName:"+loginName);
response.setContentType("text/xml;charset=UTF-8");
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
if(loginName==null||loginName.trim().length()<1){
System.out.println("名字为空");
xml+="<message><info>名字不能为空!</info></message>";
}else if(isContain(loginName)){
System.out.println("名字存在");
xml+="<message><info>这个名字已经存在!</info></message>";
}else{
System.out.println("名字不存在,可以使用");
xml+="<message><info>此名字可以使用</info></message>";
}
System.out.println("xml:"+xml);
response.getWriter().write(xml);
}
//判断输入的名字是否在定义好的数组中存在
private boolean isContain(String loginName) {
String[] users = new String[] { "Jim", "Tom", "Jack" };
for (int i = 0; i < users.length; i++) {
if (users[i].equals(loginName))
return true;
}
return false;
}
lgl669 2009-06-16
ajax  实例
Global site tag (gtag.js) - Google Analytics