Ajax 的几种方法应用

一,js实现ajax异步请求,简单例子

try.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'try.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
		function showHint(str)
		{
				var xmlhttp;
				if (str.length==0){ 
		 			 document.getElementById("txtHint").innerHTML="";
		 			 return;
				  }
				if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		  			xmlhttp=new XMLHttpRequest();
		  		}else{// code for IE6, IE5
		 			 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		 		 }
				xmlhttp.onreadystatechange=function() {
					  if (xmlhttp.readyState==4 && xmlhttp.status==200){
		    				document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
		 			   }
				  }
				xmlhttp.open("GET","LoginServlet?op="+str,true);
				xmlhttp.send(null);
		}
	</script>
  </head>
  
  <body>
    <h3>请在下面的输入框中键入字母(A - Z):</h3>
    <form action=""> 
		姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />
	</form>
	<p>建议:<span id="txtHint"></span></p> 
  </body>
</html>

  LoginServlet 

最后启动服务器,访问try.jsp 输出 a ,即可马上出现 apple

package com.dkt.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.dkt.dao.UserJdbc;

public class LoginServlet extends HttpServlet {

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

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String op = request.getParameter("op");
		System.out.println("op----------->"+op);
		if (("a").equals(op)) {
			request.setAttribute("aaa", "apple");
			PrintWriter out = response.getWriter();
			out.print("apple");//responseText;
			out.flush();
			out.close();
		}
		
	}

}

二,ajax 在 jquery 中封装后的应用 的 get(),post() 方法

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'ajax.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript">
  		$(function(){
  			$("input[name='so']").click(function(){
/*  			// ajax
  				$.ajax({
  					url:"AjaxSer",
  					type:"post",
  					data:{
  						one:$("input[name='one']").val(),
  						two:$("input[name='two']").val()
  					},
  					dataType:"json",
  					// arg是个集合
  					success:function(arg){
  						$.each(arg,function(i,item){
	  						var temp = "<tr><td>"+item.id+"</td><td>"+item.name+"</td><td>"+item.password+"</td><td>"+item.email+"</td><td>"+item.telphone+"</td></tr>";
	  						$("table").append(temp);
  						});
  					}
  				});  */
  				
/*  				//   get()方法   form表单中submit会提交表单,就会刷新页面。1,阻止表单提交  2,submit改为button
  			$.get("AjaxSer",
  					$("form").serialize(),
  					function(arg){
  						alert("get方法,只有请求成功才执行回执函数1");
  						$.each(arg,function(i,item){
	  						var temp = "<tr><td>"+item.id+"</td><td>"+item.name+"</td><td>"+item.password+"</td><td>"+item.email+"</td><td>"+item.telphone+"</td></tr>";
	  						$("table").append(temp);
  						});
  					},"json");*/
  					
  			//  post方法
  			$.post("AjaxSer",
  					{one:$("input[name='one']").val(),two:$("input[name='two']").val()},
  					function(arg){
  						$.each(arg,function(i,item){
	  						var temp = "<tr><td>"+item.id+"</td><td>"+item.name+"</td><td>"+item.password+"</td><td>"+item.email+"</td><td>"+item.telphone+"</td></tr>";
	  						$("table").append(temp);
  						});
  					},"json");
  				
  			});
  			//   ajax 加载html文件
  			$("#loadBt").click(function(){
  				$("#load").load("ind.jsp",{name:"小白",sex:"女"},function(){alert("加载完毕,请求成功与否都执行!");});
  			});
  			
  		});
  
  
  </script>
  </head>
  
  <body>
  <form>
	    条件一:姓名<input type="text" name="one" value=""/>
	    条件二:电话<input  type="text" name="two" value=""/><br/>
	    爱好:<input type="checkbox" value="吃饭"  name="hobby">吃饭
	    <input type="checkbox" value="睡觉" name="hobby">睡觉
	    <input type="checkbox" value="打豆豆" name="hobby">打豆豆
	    <input type="checkbox" value="玩游戏" name="hobby">玩游戏
	    <input type="button" value="检索" name="so">
    </form>
    <table border="1px" width="50%" height="200px">
    	<th>学号</th>
    	<th>姓名</th>
    	<th>密码</th>
    	<th>邮箱</th>
    	<th>电话</th>
    </table>
    <button id="loadBt" type="button">加载html文件</button>
    <div id="load"></div>
  </body>
</html>

加载的 ind.jsp 页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  
  <%
  String name= request.getParameter("name");
  String sex = request.getParameter("sex");
  request.setAttribute("name",name);
  request.setAttribute("sex",sex);
   %>
    得到的参数:姓名:${name }<br/>
    性别:${sex }
  </body>
</html>

 后台接受ajax传送的数据和响应页面

package com.direct.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

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

import com.direct.dao.SosAjax;
import com.direct.entity.UserInfo;
import com.google.gson.Gson;

public class AjaxSer extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String one = request.getParameter("one");
		String two = request.getParameter("two");
/*		String[]  hobby = request.getParameterValues("hobby");
//		hobby = new String(hobby.getBytes("iso-8859-1"), "utf-8");
//		System.out.println("hobby--------->"+hobby);
		
		for (String str : hobby) {
			str = new String(str.getBytes("iso-8859-1"), "utf-8");
			System.out.println("爱好:"+str);
		}*/
//		one = new String(one.getBytes("iso-8859-1"), "utf-8");  此句get()时用
		System.out.println(one);
		System.out.println(two);
		ArrayList<UserInfo> list =  new SosAjax().validate(two, one);
		Gson gson = new Gson();
		String json = gson.toJson(list);//直接转化成json格式
		System.out.println(json);
		
		out.print(json);//响应ajax异步请求
		out.flush();
		out.close();
	}

}

 三,jsonp的简单实现ajax跨域请求

http://localhost:8082/webAjax/js/web.js

$(function(){
    cross_domain({content:"跨域取值"})
})

 本项目下的jsp  jsonp.jsp

引入上面的web.js

需要两个项目同时开启服务器

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'jsonp.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
 	  <script type="text/javascript" src="js/jquery.js"></script><%--这句必须放在第一行,不然就不能使用$ --%>
	  <script type="text/javascript" src="http://localhost:8082/webAjax/js/web.js"></script>
  <script type="text/javascript">
  		alert("hahah");
  	var web = function(data){
  		alert("jsonp中传来的js值----"+data.content);
  	}
  
  $(function(){
  	$.ajax({
  		async:"false",
  		type:"post",
  		url:"http://localhost:8082/webAjax/JsonpSer",   // 请求到跨域
  		dataType:"jsonp",
  		//   传递给请求处理程序或者动态页面的变量名称,用于获取回调函数名称
  		jsonp:"callback",   
  		//  自定义json回调函数,默认jQuery自动生成的随机数
  		jsonpCallback:"fuliWeb",
  		success:function(da){
  			alert(da.name);
  		},
  		error:function(){
  			alert("请求出错!1");
  		}
  	});
  
  
  });
  
  </script>
  </head>
  
  <body>
    This is my JSP page. <br>
  </body>
</html>

  

原文地址:https://www.cnblogs.com/nn369/p/8057235.html