《JavaWeb---利用JQuery实现页面无刷新动态改变页面数据》

来源:互联网 发布:泰勒展开 矩阵形式 编辑:程序博客网 时间:2024/05/16 19:52
[html] view plaincopyprint?
  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. <base href="<%=basePath%>">
  10. <title>AJAX简单示例</title>
  11. <meta http-equiv="pragma" content="no-cache">
  12. <meta http-equiv="cache-control" content="no-cache">
  13. <meta http-equiv="expires" content="0">
  14. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  15. <meta http-equiv="description" content="This is my page">
  16. <script type="text/javascript" src="jslib/jquery.js"></script>
  17. <script type="text/javascript" src="jslib/verify.js"></script>
  18. </head>
  19. <body>
  20. <!-- 此处无需添加表单,利用 JQuery向服务器提交数据。-->
  21. <input type="text"" id="inputext"/>
  22. <input type="button" value="提交" onclick="verify()"/><br/>
  23. <!-- 预留空间用于更新数据 -->
  24. <div id="div"></div>
  25. </body>
  26. </html>

[javascript] view plaincopyprint?
  1. //JavaScript
  2. function verify(){
  3. //用JQuery语法,利用id得到对应的JQuery对象。
  4. var jqObj = $("#inputext");
  5. //获取对象中的值。
  6. var value = jqObj.val();
  7. //使用get的方式将数据传的服务器,callback是服务器端数据返回后运行的回调函数名
  8. $.get("servlet/Test?inputext=" + value,null,callback);
  9. }
  10. //定义回调函数,data用于接收服务器端返回的数据
  11. function callback(data){
  12. //得到页面中的div对象
  13. var divobj = $("#div");
  14. //将返回的数据更新到div中
  15. divobj.html(data);
  16. }

[java] view plaincopyprint?
  1. package com.fenghuo.test;
  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 Testextends HttpServlet {
  9. public void doGet(HttpServletRequest request, HttpServletResponse response)
  10. throws ServletException, IOException {
  11. response.setCharacterEncoding("UTF-8");
  12. response.setContentType("text/html;charset=UTF-8");
  13. PrintWriter out = response.getWriter();
  14. String data = request.getParameter("inputext");
  15. //此处只是将数据做了简单的处理
  16. if(data == null || data.equals("")){
  17. out.write("未得到数据或数据为空!");
  18. }else{
  19. out.write("已接收数据数据:"+data);
  20. }
  21. }
  22. public void doPost(HttpServletRequest request, HttpServletResponse response)
  23. throws ServletException, IOException {
  24. doGet(request, response);
  25. }
  26. }

版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0
原创粉丝点击