zoukankan      html  css  js  c++  java
  • Web阶段:第二十章:Ajax请求

    什么是Ajax请求?
    AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。
    ajax是一种浏览器异步发起请求。局部更新页面的技术。
    1、异步发起请求
    2、局部更新页面

    原生Ajax请求的实现(了解)

        <script type="text/javascript">
        	function ajaxRequest() {
    // 	1、我们首先要创建XMLHttpRequest 
    	var xmlHttpRequest = new XMLHttpRequest();
    // 	2、调用open方法设置请求参数
    	xmlHttpRequest.open("GET", "http://localhost:8080/day17/ajaxServlet?action=javaScriptAjax", true);
    // 	4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
    	xmlHttpRequest.onreadystatechange = function(){
    	if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
    	    	alert("响应回来啦");
    	    // 	alert("服务器返回的数据是:" + xmlHttpRequest.responseText);
    	    	var jsonObj = JSON.parse( xmlHttpRequest.responseText );
    	    // 	alert( "编号:" + jsonObj.id + ",姓名:" + jsonObj.name );
    	    	document.getElementById("div01").innerHTML = "编号:" + jsonObj.id + ",姓名:" + jsonObj.name;
    		}
    	}
    // 	3、调用send方法发送请求
    	xmlHttpRequest.send();
    	alert("这是请求后面的代码");
        }
     </script>
    

    Jquery中的Ajax请求
    $.ajax方法
    url 请求的地址
    type 请求的方式GET或POST
    data 请求的参数(发送给服务器的数据)

    支持两种格式
    一:name=value&name=value
    二: { 属性名:值 }

    success 请求成功后响应的函数
    dataType 服务器回传的数据类型

    1.text返回纯文本、
    2.xml、
    3.json返回json对象

    案例:

    // ajax请求
    $("#ajaxBtn").click(function(){
    	
    	$.ajax({
    		url:"http://localhost:8080/day17/ajaxServlet",
    		type:"GET",
    		data:"action=jqueryAjax",
    		success:function(msg){
    			// 这个success的函数。一定要有一个参数。这个参数是服务器回传的数据
    			alert(msg);
    			$("#msg").html("编号是:" + msg.id + ",姓名:" + msg.name);
    		},
    		dataType:"json"
    	});
    
    });
    

    $.get方法和$.post方法
    url 请求的地址
    data 请求的数据
    callback 请求成功的回调函数
    type 响应的数据类型
    案例:

    // ajax--get请求
    $("#getBtn").click(function(){
    	$.get("http://localhost:8080/day17/ajaxServlet",{
    			action:"jqueryGet"					
    		},function(msg){
    			// msg 请求成功的回调函数。参数msg是用来接收响应的数据
    			$("#msg").html("编号是:" + msg.id + ",姓名:" + msg.name);
    		},"json");
    	
    });
    
    // ajax--post请求
    $("#postBtn").click(function(){
    	// post请求
    	$.post("http://localhost:8080/day17/ajaxServlet","action=jqueryPost",function(msg){
    		// msg 请求成功的回调函数。参数msg是用来接收响应的数据
    		$("#msg").html("post请求 编号是:" + msg.id + ",姓名:" + msg.name);
    	},"json");
    });
    

    $.getJSON方法
    url 请求的地址
    data 请求的参数
    callback 成功的回调

    getJSON 请求方式固定是GET请求,响应的数据,固定是json格式。
    案例:

    // ajax--getJson请求
    $("#getJSONBtn").click(function(){
    	// 调用
    	$.getJSON("http://localhost:8080/day17/ajaxServlet","action=jqueryGetJSON",function(msg){
    		$("#msg").html("getJSON请求  编号是:" + msg.id + ",姓名:" + msg.name);
    	});
    });
    

    表单序列化serialize()
    serialize() 方法可以把一个form表单中所有的表单项。都以字符串name=value&name=value的形式进行拼接,省去我们很多不必要的工作。

    由于$.get、$.post和getJSON这三个方法的底层都是直接或者间接地使用$.ajax()方法来实现的异步请求的调用。
    案例:

    // ajax请求
    	$("#submit").click(function(){
    		// 把参数序列化
    		// serialize() 方法可以把表单项以name=vlaue&name=value进行拼接。
    		var data = $("#form01").serialize();
    		alert(data);
    		//当我们点击这个按钮的时候,我们希望把表单中所有的表单项,
    		// 以name=value&name=value的信息,进行拼接,然后发送给服务器
    		$.getJSON("http://localhost:8080/day17/ajaxServlet","action=jquerySerialize&" + data,function(msg){
    			$("#msg").html("jquerySerialize  编号是:" + msg.id + ",姓名:" + msg.name);
    		});
    		
    	});
    

    实例:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    	<head>
    		<meta http-equiv="pragma" content="no-cache" />
    		<meta http-equiv="cache-control" content="no-cache" />
    		<meta http-equiv="Expires" content="0" />
    		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    		<title>Insert title here</title>
    		<script type="text/javascript" src="script/jquery-1.7.2.js"></script>
    		<script type="text/javascript">
    			$(function(){
    				// ajax请求
    				$("#ajaxBtn").click(function(){
    					$.ajax({
    						url : "ajaxServlet", // 请求地址
    						error:function(){   // 请求失败回调
    							alert("请求失败");
    						},
    						success:function(data){ // 请求成功回调
    							alert( data );
    						},
    						type:"POST",				// 请求的方式
    						dataType:"json",			// 返回的数据类型为json对象
    						data:{						// 请求的参数
    							action:"jqueryAjax",
    							a:12,
    							date: new Date()
    						}
    					});
    				});
    
    				// ajax--get请求
    				$("#getBtn").click(function(){
    					$.get(
    						"ajaxServlet",{
    							action:"jqueryGet",
    							a:12,
    							date:new Date()
    						},function(data){alert(data);},"json"
    					);
    				});
    				
    				// ajax--post请求
    				$("#postBtn").click(function(){
    					// post请求
    					$.post(
    						"ajaxServlet", // 请求路径
    						{				// 请求参数
    							action:"jqueryPost",
    							a:12,
    							date:new Date()
    						},
    						function(data){ alert( data ) },  // 成功的回调函数
    						"text"							// 返回的数据类型
    					);
    				});
    
    				// ajax--getJson请求
    				$("#getJsonBtn").click(function(){
    					// 调用
    					$.getJSON(
    						"ajaxServlet", 		// 请求路径
    						{					// 请求参数
    							action:"jqueryGetJSON",
    							a:12,
    							date:new Date()
    						}, 
    						function(data){ alert( data ) }  // 成功的回调函数		
    					);
    				});
    
    				// ajax请求
    				$("#submit").click(function(){
    					// 把参数序列化
    					var data = $("#form01").serialize();
    					alert(data);
    				});
    				
    			});
    		</script>
    	</head>
    	<body>
    		<div>
    			<button id="ajaxBtn">$.ajax请求</button>
    			<button id="getBtn">$.get请求</button>
    			<button id="postBtn">$.post请求</button>
    			<button id="getJsonBtn">$.getJSON请求</button>
    		</div>
    		<br/><br/>
    		<form id="form01" >
    			用户名:<input name="username" type="text" /><br/>
    			密码:<input name="password" type="password" /><br/>
    			下拉单选:<select name="single">
    			  	<option value="Single">Single</option>
    			  	<option value="Single2">Single2</option>
    			</select><br/>
    		  	下拉多选:
    		  	<select name="multiple" multiple="multiple">
    		    	<option selected="selected" value="Multiple">Multiple</option>
    		    	<option value="Multiple2">Multiple2</option>
    		    	<option selected="selected" value="Multiple3">Multiple3</option>
    		  	</select><br/>
    		  	复选:
    		 	<input type="checkbox" name="check" value="check1"/> check1
    		 	<input type="checkbox" name="check" value="check2" checked="checked"/> check2<br/>
    		 	单选:
    		 	<input type="radio" name="radio" value="radio1" checked="checked"/> radio1
    		 	<input type="radio" name="radio" value="radio2"/> radio2<br/>
    		 	<input id="submit" type="submit" />
    		</form>			
    	</body>
    </html>
    

    2)AjaxServlet的代码如下:

    package com.atguigu.servlet;
    
    import java.io.IOException;
    import java.util.Random;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.atguigu.gson.GsonTest;
    import com.google.gson.Gson;
    
    public class AjaxServlet extends BaseServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void javaScriptAjax(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		System.out.println("ajax请求过来了 a--" + request.getParameter("a"));
    		Random random = new Random(System.currentTimeMillis());
    		// 使用随机数,可以让客户端看到变化
    		response.getWriter().write(
    				new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    	}
    	
    	protected void jqueryAjax(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		System.out.println("jqueryAjax请求过来了 a--" + request.getParameter("a"));
    		Random random = new Random(System.currentTimeMillis());
    		// 使用随机数,可以让客户端看到变化
    		response.getWriter().write(
    				new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    	}
    	
    	protected void jqueryGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		System.out.println("jqueryGet请求过来了 a--" + request.getParameter("a"));
    		Random random = new Random(System.currentTimeMillis());
    		// 使用随机数,可以让客户端看到变化
    		response.getWriter().write(
    				new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    	}
    	
    	protected void jqueryPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		System.out.println("jqueryPost请求过来了 a--" + request.getParameter("a"));
    		Random random = new Random(System.currentTimeMillis());
    		// 使用随机数,可以让客户端看到变化
    		response.getWriter().write(
    				new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    	}
    	
    	protected void jqueryGetJSON(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		System.out.println("jqueryGetJSON请求过来了 a--" + request.getParameter("a"));
    		Random random = new Random(System.currentTimeMillis());
    		// 使用随机数,可以让客户端看到变化
    		response.getWriter().write(
    				new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    	}
    
    }
    
  • 相关阅读:
    Atitit. visual studio vs2003 vs2005 vs2008  VS2010 vs2012 vs2015新特性 新功能.doc
    Atitit. C#.net clr 2.0  4.0新特性
    Atitit. C#.net clr 2.0  4.0新特性
    Atitit.通过null 参数 反射  动态反推方法调用
    Atitit.通过null 参数 反射  动态反推方法调用
    Atitit..net clr il指令集 以及指令分类  与指令详细说明
    Atitit..net clr il指令集 以及指令分类  与指令详细说明
    Atitit.变量的定义 获取 储存 物理结构 基本类型简化 隐式转换 类型推导 与底层原理 attilaxDSL
    Atitit.变量的定义 获取 储存 物理结构 基本类型简化 隐式转换 类型推导 与底层原理 attilaxDSL
    Atitit.跨语言反射api 兼容性提升与增强 java c#。Net  php  js
  • 原文地址:https://www.cnblogs.com/javawxid/p/12812099.html
Copyright © 2011-2022 走看看