zoukankan      html  css  js  c++  java
  • 一个简单的aJax——后台用servlet技术

    示例:webDemo

    一、客户端

    <%--
      Created by IntelliJ IDEA.
      User: Administrator
      Date: 15-12-2
      Time: 上午5:41
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title></title>
          <script type="text/javascript" src="js/jquery-1.11.2.js"></script>
          <script type="text/javascript">
              function  ajaxTest(){
                  $.ajax({
                      type: "POST",
                      url: "mytest",
                      data: "name=John&location=Boston",
                      success: function(data){
                          alert( "Data Saved: " + data );
                      }
                  });
              }
    
          </script>
      </head>
      <body>
        <form action="mytest" method="post">
          <input name="name">
          return:${name}
          <input value="提交" type="submit">
    
            <input value="ajax" type="button" onclick="ajaxTest();">
        </form>
      </body>
    </html>

    二、服务端

    package com.wql.test;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    @WebServlet("/mytest")
    public class Test extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            String name=req.getParameter("name");
            req.setAttribute("name",name);
            //----ajax
            PrintWriter writer =  resp.getWriter();
            //获取ajax的请求数据
            String reqParam1 = req.getParameter("name");
            String reqParam2 = req.getParameter("location");
            //调用PrintWriter的print或write方法均可将数据写入请求页面的ajax请求的回调函数——data
    //        writer.print("ajaxName of print");
            writer.print(reqParam1);//John 将ajax的请求中的数据写出
    //        writer.write("ajaxName");
    
    //        req.getRequestDispatcher("index.jsp").forward(req, resp);
        }
    
    }
  • 相关阅读:
    Axure RP 9 Beta 开放下载(更新激活密钥和汉化包)
    Android 解决NestedScrollView 嵌套 RecyclerView出现的卡顿,上拉刷新无效
    上周热点回顾(8.27-9.2)团队
    上周热点回顾(8.20-8.26)团队
    上周热点回顾(8.13-8.19)团队
    上周热点回顾(8.6-8.12)团队
    阿里云MVP第6期招募与博客园合作启动团队
    上周热点回顾(7.30-8.5)团队
    上周热点回顾(7.23-7.29)团队
    上周热点回顾(7.16-7.22)团队
  • 原文地址:https://www.cnblogs.com/wql025/p/5022820.html
Copyright © 2011-2022 走看看