歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery實現的Ajax小例子

jQuery實現的Ajax小例子

日期:2017/3/1 10:20:16   编辑:Linux編程

jQuery實現的Ajax小例子

jsp代碼:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <title>My JSP 'index.jsp' starting page</title>
  10. <meta http-equiv="pragma" content="no-cache">
  11. <meta http-equiv="cache-control" content="no-cache">
  12. <meta http-equiv="expires" content="0">
  13. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  14. <meta http-equiv="description" content="This is my page">
  15. <!--
  16. <link rel="stylesheet" type="text/css" href="styles.css">
  17. -->
  18. <script type="text/javascript" src="<%=basePath%>js/jquery-1.6.4.min.js"></script>
  19. </head>
  20. <script type="text/javascript">
  21. function ajaxrequest(){
  22. $.ajax({
  23. type:"get",
  24. url:"lpm",
  25. dataType:"text",
  26. data:"name=hello world&age=15",
  27. success:function(msg){
  28. $("#name").val(msg);
  29. }
  30. });
  31. }
  32. function ajaxre2(){
  33. $.get("lpm",{name:"lpm",age:"25"},function(msg){
  34. $("#wenben").val(msg);
  35. });
  36. }
  37. </script>
  38. <body>
  39. <input type="button" id="name" value="按鈕" onclick="ajaxrequest()" />
  40. <input type="text" id="wenben" onfocus="ajaxre2()"/>
  41. </body>
  42. </html>

web.xml配置servlet:

  1. <servlet>
  2. <servlet-name>lpm</servlet-name>
  3. <servlet-class>com.chinasoft.lpm</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>lpm</servlet-name>
  7. <url-pattern>/lpm</url-pattern>
  8. </servlet-mapping>

servlet代碼:

  1. package com.chinasoft;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. public class lpm extends HttpServlet {
  9. public void doGet(HttpServletRequest request, HttpServletResponse response)
  10. throws ServletException, IOException {
  11. response.setContentType("text/html");
  12. PrintWriter out = response.getWriter();
  13. String name=request.getParameter("name");
  14. String age=request.getParameter("age");
  15. out.println(name+":"+age);
  16. }
  17. public void doPost(HttpServletRequest request, HttpServletResponse response)
  18. throws ServletException, IOException {
  19. this.doGet(request, response);
  20. }
  21. }
Copyright © Linux教程網 All Rights Reserved