jquery的ajax

jquery是一个优秀的js框架,自然对js原生的ajax进行了封装,封装后的ajax的操作方法更简洁,功能更强大,与ajax操作相关的jquery方法有如下几种,但开发中经常使用的有三种

1)$.get(url, [data], [callback], [type])

2)$.post(url, [data], [callback], [type])

 

其中:

url:代表请求的服务器端地址

data:代表请求服务器端的数据(可以是key=value形式也可以是json格式)

callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)

type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换)

常用的返回类型:text、json、html等

 

3)$.ajax( { option1:value1,option2:value2... } ); ---- 以后在掌握

常用的option有如下:

async:是否异步,默认是true代表异步

data:发送到服务器的参数,建议使用json格式

dataType:服务器端返回的数据类型,常用text和json

success:成功响应执行的函数,对应的类型是function类型

type:请求方式,POST/GET

url:请求服务器端地址

例如:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">


	function fn1(){
		//get异步访问
		$.get(
			"/WEB22/ajaxServlet2", //url地址
			{"name":"张三","age":25}, //请求参数
			function(data){ //执行成功后的回调函数
				//{"name":"tom","age":21}
				alert(data.name);
			},
			"json"
		);
	}
	function fn2(){
		//post异步访问
		$.post(
			"/WEB22/ajaxServlet2", //url地址
			{"name":"李四","age":25}, //请求参数
			function(data){ //执行成功后的回调函数
				alert(data.name);
			},
			"json"
		);
	}
	function fn3(){
		$.ajax({
			url:"/WEB22/ajaxServlet2",
			async:true,
			type:"POST",
			data:{"name":"lucy","age":18},
			success:function(data){
				alert(data.name);
			},
			error:function(){
				alert("请求失败");
			},
			dataType:"json"
		});
	}
</script>

</head>
<body>
	<input type="button" value="get访问服务器端" onclick="fn1()"><span id="span1"></span>
	<br>
	<input type="button" value="post访问服务器端" onclick="fn2()"><span id="span2"></span>
	<br>
	<input type="button" value="ajax访问服务器端" onclick="fn3()"><span id="span2"></span>
	<br>
</body>
</html>

  前台中获取及返回:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxServlet2 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		
		System.out.println(name+"  "+age);
		
		
		//java代码只能返回一个json格式的字符串
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write("{"name":"汤姆","age":21}");
		
	}

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

  

 后台将集合转换成json:

 

 

原文地址:https://www.cnblogs.com/wuxu/p/10911719.html