jQuery $.ajax()异步请求

Reads: 2195 Edit

资料参考 http://jquery.cuishifeng.cn/jQuery.Ajax.html

ajax() 方法用于执行 AJAX(异步 HTTP)请求。

新建ajax.jsp

2201

修改 GetInfoServlet.java

package com.test;


import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class GetInfoServlet 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 {


        String method = req.getParameter("method");
        System.out.println("---- GetInfoServlet method=" + method);

        if(null != method){
            if ( method.toLowerCase().equals("handleGetRequest".toLowerCase())){
                handleGetRequest(req,resp);
            }else if( method.toLowerCase().equals("handleAjaxRequest".toLowerCase())){
                handleAjaxRequest(req,resp);
            }
        }


    }

    private void handleGetRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
         System.out.println("--- handleGetRequest actions---");
         response.setContentType("application/json;charset=utf-8");
         response.setCharacterEncoding("UTF-8");
         PrintWriter out = response.getWriter();

         JSONObject jsonObj = new JSONObject();
         jsonObj.put("name","zhangsan");
         jsonObj.put("age", 30);
         out.println(jsonObj.toString());
         out.flush();
         out.close();
    }


    private void handleAjaxRequest(HttpServletRequest request, HttpServletResponse response)throws IOException{
        System.out.println("---handleAjaxRequest actions request ");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("name", "wangwu1");
        jsonObj.put("age", 22);
        out.println(jsonObj.toString());

        //模拟耗時操作
        try
        {
            Thread.sleep(1000*3);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        out.flush();
        out.close();

    }
}

然后运行 mvn tomcat7:run命令后,访问 ajax.jsp页面查看效果。

关于作者

王硕,网名信平,十多年软件开发经验,业余架构师,精通Java/Python/Go等,喜欢研究技术,著有《PyQt 5 快速开发与实战》《Python 3.* 全栈开发》,多个业余开源项目托管在GitHub上,欢迎微博交流。


Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。