1、jQuery.get( url, [data], [callback] ):使用GET方式来进行异步请求
1.1 参数:
url (String) : 发送请求的URL地址.
data (Map) : (可选) 要发送给服务器的数据,以 Key/value 的键值对形式表示,会做为jQueryString附加到请求URL中。
callback (Function) : (可选) 载入成功时回调函数(只有当Response的返回状态是success才是调用该方法)。
请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。
1.2 jQuery的Ajax与Java通过GET方式交互
1.2.1 html代码
<body> <div id="main"> <button id="myBut">Ajax获取数据</button> <div id="container"></div> </div> </body>
1.2.2 style代码
<style type="text/css"> #main { margin: 0 auto; width: 400px; } #container { width: 400px; height: 300px; border: 1px dashed #666; text-align: center; line-height: 300px; } </style>
1.2.3 Javascript代码
<script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $(function() { $('#myBut').click(function() { $.get("JqueryAjaxServlet", { age : 18, name : "zhang" }, function(data, textStatus) { var container = $('#container'); var resultData = $.parseJSON(data); var age = resultData.age; var name = resultData.name; container.html("name:" + name + "," + "age:" + age); }); }); }); </script>
1.2.4 JqueryAjaxServlet.java代码
public class JqueryAjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String age = request.getParameter("age"); String name = request.getParameter("name"); String personJSON = "{\"name" + "\":\"" + name + "\"," + "\"age" + "\":" + age + "}"; System.out.println(personJSON); response.getWriter().write(personJSON); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
1.2.5 web.xml代码
<servlet> <servlet-name>JqueryAjaxServlet</servlet-name> <servlet-class>com.jquery.ajax.com.JqueryAjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>JqueryAjaxServlet</servlet-name> <url-pattern>/JqueryAjaxServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
时间: 2024-12-23 13:43:55