jquery+servlet实现ajax

说明

依赖

依赖 jackson jar包:

  • jackson-annotations-2.3.1.jar
  • jackson-core-2.3.1.jar
  • jackson-databind-2.3.1.jar

Servlet代码

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

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 com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet( urlPatterns="/testJson"  )
public class HelloLucyServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //一定是 text/json,否则浏览器不识别json
        resp.setContentType("text/json;charset=utf-8");
        Map map=new HashMap();
        map.put("name", "李雷");
        map.put("age", 20);

        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(map);

        PrintWriter pw = resp.getWriter();
        pw.write(json);
        pw.close();//关闭
    }
}

关键代码1

必须写:

resp.setContentType("text/json;charset=utf-8");

这样浏览器的响应头才会显示 json,如下:

这样浏览器才能识别到 json格式的数据

关键代码2

ObjectMapper om=new ObjectMapper();
String json=om.writeValueAsString(map);

其作用是将 Map 对象转换成 json 字符串

详见链接:

Jackson 处理json(ObjectMapper)

Jackson目录

html

引入jquery

<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>

js代码

<script type="text/javascript">
$.ajax({
    url:'testJson',//请求的url
    type:'get', //请求方式,GET或POST
    data:{

    },
    dataType:'json',    
    success:function(data){//成功时执行该函数
        console.log(data)
    },
    error:function(xhr,textStatus){//错误时执行该函数
        console.log('错误')
        console.log(xhr)
        console.log(textStatus)
    }
})
</script>

原文出处:http://malaoshi.top/show_1IX2chMedQ9h.html