一个简单的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);
    }

}

 

posted @ 2015-12-06 02:56  Tom1997  阅读(1352)  评论(0编辑  收藏  举报