28.Jquery的ajax之load方法
JQuery中的load()方法
* load()方法执行的话,需要使用对象.load()方法
* load方法的参数
* url -- 访问的服务器端地址(xxxServlet)
* data -- 以key:value的形式发送数据(都是json的数据)
* callback -- 回调函数,服务器端响应成功了,该函数就会执行了(目的:获取服务器端响应的数据,操作)
* 回调函数的3个参数
* data -- 返回的内容
* textStatus -- 代表的请求的状态的
* XMLHttpRequest -- 底层对象返回
* 默认使用 GET 方式 - 传递附加参数时自动转换为 POST 方式
ajax1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${ pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
// 先使用load()方法
/**
load()方法的3个参数
1.url 代表连接服务器资源的地址
2.data 代表的是给服务器发送的请求参数,尽量使用json格式的数据
3.callback 代表回调函数,服务器端响应后,调用回调函数
*data参数是服务器端响应的数据
*/
$("input[type='button']").click(function(){
var url="${pageContext.request.contextPath}/ajax1";
var jsonData={"pname":"张三"};
//发送异步的请求,使用load()方法
$(this).load(url,jsonData,function(data){
//回调函数,目的:获取到响应的内容
//$("#h4Id").text(data);
//服务器响应的是json格式的字符串,data表示Json对象,需要用eval()函数执行一次
var p=eval("("+data+")");
$("#h4Id").text(p.name);
});
});
});
</script>
</head>
<body>
<h3>jQuery中的ajax的入门</h3>
<input type="button" value="点击" />
<h4 id="h4Id"></h4>
</body>
</html>
Ajax1Servlet:
public class Ajax1Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
System.out.println("请求成功了!");
//获取请求的方式
String method=request.getMethod();
System.out.println("请求方式是:"+method);
//接收请求参数
String pname=request.getParameter("pname");
System.out.println("pname:"+pname);
response.setContentType("text/html;charset=utf-8");
//响应字符串
//response.getWriter().print("您好 ajax");
//响应json数据格式的字符串
String j="{\"name\":\"赵四\"}";
response.getWriter().print(j);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

浙公网安备 33010602011771号