我是靠谱客的博主 温婉故事,最近开发中收集的这篇文章主要介绍ajax总结,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1、从 Web 表单中获取所有需要的参数;
2、建立要连接的 URL 
3.设置服务器在完成后要运行的函数(回调函数)
4、打开到服务器的连接
5、进行相关连接设置,包括缓存清空设置、等

5、发送请求

javascript代码:

<script type="text/javascript">
	  //声明XMLHttpRequest对象
	  var xmlHttp;
	  //异步请求验证用户注册账号是否可用
	  function checkUserName(){
	      //1、从 Web 表单中获取所有需要的参数
	      var userName=document.registerForm.user.value;
	      if(userName.length<6){
	         alert("请填写用户名称");
	         return;
	      }	      
	      //2、建立要连接的 URL
	      var url="checkNameServlet?userName="+userName;
	      //我们使用get方法进行异步提交,故对可能存在中文数据进行编码
	      url=encodeURI(encodeURI(url));
	      //3.设置服务器在完成后要运行的函数
	      //a)创建XMLHttpRequest对象
	      xmlHttp = new XMLHttpRequest();	      
	      //b)设置回调函数:主要告诉服务器数据返回后应该怎么处理
	      xmlHttp.onreadystatechange=handler;
	      
	      //4、打开到服务器的连接
	      xmlHttp.open("get",url,true);	 
	       
	      xmlHttp.setRequestHeader("If-Modified-Since","0");    
	      //5、发送请求
	      xmlHttp.send(null);
	  }
	  //声明回调函数
	  function handler(){
	     //就绪状态是 4 而且状态码是 200,就可以处理服务器的数据了,而且这些数据应该就是要求的数据
	     if(xmlHttp.readyState==4){
	       //响应已完成,可以访问服务器响应并使用它
		   if(xmlHttp.status==200){
		     var data=xmlHttp.responseText;
		     var txtNameObj = document.registerForm.user;
		     if(parseInt(data)==0){
		        txtNameObj.style.borderColor="green";
		        txtNameObj.style.color="black";
		     }else{
		        txtNameObj.style.borderColor="red";
		        txtNameObj.style.color="red";
		     }
		   }
	     }
	  }
	  //异步:post
	  //异步请求验证用户注册账号是否可用
	  function initCheckCode(){	     
	      //2、建立要连接的 URL
	      var url="checkCode";	    
	      //3.设置服务器在完成后要运行的函数
	      //a)创建XMLHttpRequest对象
	      xmlHttp = new XMLHttpRequest();	      
	      //b)设置回调函数:主要告诉服务器数据返回后应该怎么处理
	      xmlHttp.onreadystatechange=fillCode;	      
	      //4、打开到服务器的连接
	      xmlHttp.open("post",url,true); 	       
	      xmlHttp.setRequestHeader("If-Modified-Since","0"); 
	      xmlHttp.setRequestHeader("Content-type",
                         "application/x-www-form-urlencoded");
	      //5、发送请求
	      xmlHttp.send(null);
	  }
	  //回调函数
	  function fillCode(){
	   if(xmlHttp.readyState==4){
	       //响应已完成,可以访问服务器响应并使用它
		   if(xmlHttp.status==200){
		     var code = xmlHttp.responseText;
		      //alert(code);
		      document.getElementById("check_code").innerHTML=code;
		   }
	    }
	  }
//只有勾选已同意协议,才可以进行表单的提交	 
	  function agree(obj){
	    if(obj.checked==true){
	       document.getElementById("btn_smt").disabled=false;
	    }else{
	    	document.getElementById("btn_smt").disabled=true;
	    }
	  }
	  
	  //表单的onsubmit事件
	  function checkData(){
	     if(document.registerForm.pwd.value.length<6){
	       alert("password length less than 6");
	       return false;
	     }
	     return true;	  
	  }
	</script>
对应的网页的html的form表单:
<form action="" method="post" name="registerForm"
				  οnsubmit="return checkData();">
					<dl>
						<dt>用户名</dt>
						<dd><input type="text" name="user" class="text" οnblur="checkUserName();" /></dd>
					</dl>
					<dl>
						<dt>密码</dt>
						<dd><input type="password" name="pwd" class="text"/></dd>
					</dl>
					<dl>
						<dt>确认密码</dt>
						<dd><input type="password" name="repwd" class="text"/></dd>
					</dl>
					<dl>
						<dt>邮箱</dt>
						<dd><input type="text" name="email" class="text"/></dd>
					</dl>
					<dl>
						<dt>验证码</dt>
						<dd><input type="text" name="code" class="text" size="10" style="width:58px;"/>
						 <span id="check_code" style="position:relative;top:-2px;width:120px;"></span> 
						<a οnclick="initCheckCode();" style="cursor:pointer;">看不清,换一张</a>
						</dd>
					</dl>
					<dl>
						<dt> </dt>
						<dd><input type="submit" id="btn_smt" value="立即注册" class="submit" disabled="disabled"/>
						<input type= "checkbox" οnclick="agree(this);"/>阅读并同意<a href="" class="forget">服务协议</a></dd>
					</dl>
				</form>

java servlet代码,传递数字:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckNameServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {		
		String name=request.getParameter("userName");
		name=URLDecoder.decode(name,"UTF-8");
		int flag=0;
		//模拟查询数据库,判断用户名称是否已存在
		String nameList="jack,刘一手,xuebagou123";
		if(nameList.indexOf(name)!=-1){
			//用户名称已存在
			flag=1;
		}
		//异步处理后的返回:text/xml
		response.setContentType("text/xml");
		PrintWriter out = response.getWriter();
		//输出给客户端请求的响应结果
		out.println(flag);
		
		out.flush();
		out.close();
	}

}

java servlet代码 传递字符串:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckCode extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
							throws ServletException, IOException {
		this.doPost(request, response);

	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {		
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		Random rd = new Random();
		char[] chs = new char[4];
		int num=-1,index=0;
		while(true){
			num = rd.nextInt(122-48+1)+48;
			if((num>=58&&num<=64)||(num>=91&&num<=96)){
				continue;
			}
			chs[index++]=(char)num;
			if(index>3){
				break;
			}
		}
		String code = new String(chs);
		request.getSession().setAttribute("check_code", code);
		
		out.println(code);
		
		out.flush();
		out.close();	
	}

}

java servlet代码 传递xml格式的字符串:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SysManager extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int type=Integer.parseInt(request.getParameter("type"));
		List<Menu> datas=new MenuDao().queryMenu(type);
		request.setAttribute("parentMenus",datas);
		if(type==0){
			//同步请求
			request.getRequestDispatcher("menu.jsp").forward(request, response);
		}else{
			//异步请求
			response.setContentType("text/xml;charset=utf-8");
			PrintWriter out =response.getWriter();
			//把要返回的数据已xml格式发送给客户端
			StringBuffer buff = new StringBuffer();
			buff.append("<menus>");
			for(Menu me: datas){
				buff.append("<menu>")
					.append("<id>").append(me.getId()).append("</id>")
					.append("<title>").append(me.getTitle()).append("</title>")
					.append("<url>").append(me.getUrl()).append("</url>")
					.append("<pno>").append(me.getParentId()).append("</pno>")
				    .append("</menu>");
			}			
			buff.append("</menus>");
			//输出数据到客户端
			out.println(buff.toString());
			
			out.flush();
			out.close();
		}
	}

}
/*
 * xml格式:
<menus>
   <menu>
       <id></id>
       <title></title>
       <url></url>
       <pno></pno>
   </menu>
</menus>
 */

jsp代码,以及如何在异步请求时对div快进行处理:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>menu.jsp</title>
    <script type="text/javascript">
      var xmlHttp=new XMLHttpRequest();
      function showMenu(childMenuDivNo){
        //设置请求的url
        var url="sysManager?type="+childMenuDivNo;
        //设置回调函数
        xmlHttp.onreadystatechange=handler;
        xmlHttp.open("get",url,true);
        xmlHttp.send(null);
      }
      //回调函数
      function handler(){
         if(xmlHttp.readyState==4){
           if(xmlHttp.status==200){
                //alert(xmlHttp.responseText);
                var xmldoc = xmlHttp.responseXML;
                //alert(xmldoc);
                
                var titleArray = xmldoc.getElementsByTagName("title");
                var content="<ul style='list-style-type:none;'>";
                for(var i=0;i<titleArray.length;i++){
                   //alert(titleArray[i].firstChild.data);
                   content+="<li>"+titleArray[i].firstChild.nodeValue+"</li>";
                }  
                content+="</ul>";
                //alert(content);           	
             	//显示子菜单div
             	var pno=
             	  xmldoc.getElementsByTagName("pno")[0].firstChild.nodeValue;
             	
		      	var childMenuDiv=document.getElementById("menu_"+pno);
		      	
		      	childMenuDiv.innerHTML=content;
		      	
		      	if(childMenuDiv.style.display=="block"){
		      		childMenuDiv.style.display="none";
		      	}else{
		      	    childMenuDiv.style.display="block";
		      	}	
	       }
         }
      }
    </script>
  </head>
  <body> 
    <c:forEach items="${requestScope.parentMenus}" var="menu">
       <label οnclick="showMenu('${menu.id }');">${menu.title }</label>
       <div id="menu_${menu.id }" style="display:none;width:150px;">
         
       </div><br/>
    </c:forEach>
  </body>
</html>  

java servlet代码:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xiaogang.demo02.DBConnection;

public class FillStudent extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String classNo = request.getParameter("classno");
        
        Connection con = DBConnection.getDbcon();
        String sql="select * from t_student where classno=?";
        PreparedStatement pst;
        StringBuffer buff = new StringBuffer();
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, classNo);
			ResultSet rs = pst.executeQuery();
			buff.append("<students>");
			while(rs.next()){
				buff.append("<student>")
					.append("<no>").append(rs.getInt(1)).append("</no>")
					.append("<name>").append(rs.getString(2)).append("</name>")
					.append("<cno>").append(rs.getString(3)).append("</cno>")
					.append("</student>");
			}
			buff.append("</students>");
			rs.close();
			pst.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBConnection.closeDbcon(con);
		
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter pw = response.getWriter();
		pw.println(buff.toString());
		pw.flush();
		pw.close();
	}
}
/*
<students>
  <student>
     <no></no>
     <name><name>
     <cno></con>
  </student>
</students>
 */

jsp代码,以及如何对下拉列表进行处理:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'selectCacade.jsp' starting page</title>
    <script type="text/javascript">
      var xmlHttp = new XMLHttpRequest();
      function fillStudentSel(selObj){
          var selVal=selObj.value;
          if(selVal==-1){
             document.getElementById("stu_sel").length=1;
             return;
          }
          //发送异步请求:查询选择班级的所有学生信息
          var url = "fillStudent";
          xmlHttp.open("post",url,true);
          xmlHttp.setRequestHeader("Content-Type",
             "application/x-www-form-urlencoded");
          var param ="classno="+selVal;
          xmlHttp.onreadystatechange=fillStudents;
          xmlHttp.send(param);
      }
      function fillStudents(){
         if(xmlHttp.readyState==4){
           if(xmlHttp.status==200){
           	   //alert(xmlHttp.responseText);
           	   operatorSel(xmlHttp.responseXML);
           }
         }
      }
      //动态创建和添加option选项对象
      function operatorSel(xmldoc){
        var noList = xmldoc.getElementsByTagName("no");
        var nameList = xmldoc.getElementsByTagName("name");
        
        document.getElementById("stu_sel").length=1;
        
        for(var i=0;i<noList.length;i++){
	        //创建<option>元素
	        var optionObj=document.createElement("option");
	        optionObj.value=noList[i].firstChild.data;
	        optionObj.text=nameList[i].firstChild.data;
	        //把option标签追加的下拉列表中
	        document.getElementById("stu_sel").appendChild(optionObj);
        }
              
      }
    </script>
  </head>
  <body>     
    	班级:
    	<select name="classroom" οnchange="fillStudentSel(this);">
    		<option value="-1">--请选择--</option>
    		<option value="J160501">J160501</option>
    		<option value="J150501">J150501</option>
    		<option value="J150402">J150402</option>
    	</select>
    	学生:
    	<select id="stu_sel"  name="student">
    		<option>--请选择--</option>    		
    	</select>
    	<br>
  </body>
</html>



最后

以上就是温婉故事为你收集整理的ajax总结的全部内容,希望文章能够帮你解决ajax总结所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部