29.jquery的ajax之post和get方法

JQuery中的get()方法
  * 注意:使用$.get()方式来调用
  * 该方法的参数
    * url -- 请求的路径
    * data -- 发送的数据(json)
    * callback -- 回调函数载入成功时回调函数。
    * type -- 返回内容格式,xml, html, script, json, text, _default。

JQuery中的post()方法(开发中使用比较多的)
  * 注意:使用$.post()方式来调用
  * 该方法的参数
    * url -- 请求的路径
    * data -- 发送的数据(json)
    * callback -- 回调函数载入成功时回调函数。
    * type -- 返回内容格式,xml, html, script, json, text, _default。

<%@ 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(){
		$("input[type='button']").click(function(){
			//使用post方法
			var url="${pageContext.request.contextPath}/ajax1";
			var jsonData={"pname":"王五"};
			$.post(url,jsonData,function(data){
			
				alert(data.name);
			},"json")
		});
	});
</script>
</head>
<body>

<h3>jQuery中的ajax的入门(使用$.post方法)</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);
	}
}

  

posted @ 2018-02-24 12:28  一日看尽长安花cxjj  阅读(231)  评论(0)    收藏  举报