微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax_02-结合jQuery简单的get与post请求

1、jsp页面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <%
 8 pageContext.setAttribute("APP_PATH",request.getcontextpath());
 9 %>
10 <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
11 <title>Insert title here</title>
12 </head>
13 <body>
14 
15     <input type="button" onclick="get()" value="使用JQuery演示 get方法"/>
16     <input type="button" onclick="post()" value="使用JQuery演示 post方法"/>
17      <div id="div01"  style="width: 100px ; height: 100px ; border: 1px solid blue; ">
18      </div>
19       <div id="div02"  style="width: 100px ; height: 100px ; border: 1px solid blue; ">
20      </div>
21 </body>
22 <script type="text/javascript">
23 //$.get(URL,callback);
24     function get() {
25         $.get("/day16/DemoServlet02?name=aa&age=19",function(data,status) {
26             alert("结果是:"+data);
27             $("#div01").text("aaa="+data);
28         });
29     }
30     function post(){
31         $.post("${APP_PATH}/DemoServlet02?name=aa&age=19",status){
32             $("#div02").text("post="+data);
33         });
34     }
35 </script>
36 </html>@H_938_404@ 

关键点:$.get("url",function(data,status));其中data就是后台传过来的数据 将get换为post即为post请求

2、后台java代码

 1 package com.itheima.servlet;
 2 
 3 import java.io.IOException;
 4 import javax.servlet.servletexception;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 /**
10  * Servlet implementation class DemoServlet02
11  */
12 public class DemoServlet02 extends HttpServlet {
13     protected void doGet(HttpServletRequest request,HttpServletResponse response) throws servletexception,IOException {
14 
15         String name = request.getParameter("name");
16         int age = Integer.parseInt(request.getParameter("age"));
17         System.out.println("收到了请求..."+name+"="+age);
18         
19         response.setContentType("text/html;charset=utf-8");
20         response.getWriter().write("给你一份数据");
21     }
22 
23     /**
24      * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response)
25      */
26     protected void doPost(HttpServletRequest request,IOException {
27         // Todo Auto-generated method stub
28         System.out.println("将请求转给get处理");
29         doGet(request,response);
30     }
31 
32 }@H_938_404@ 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐