jsp的代码,需要引入jquery.js
function init(){
$.ajax({
url:'ajaxServlet',
type:'post',
dataType:'json',//服务器端返回的数据格式是json
data: {},//发给服务器端的数据
success:function(data){ //data:服务器端返回给浏览器端的数据
alert(JSON.stringify(data));
},
error:function (XMLHttpRequest, textStatus) {
alert('发生错误')
console.log(xhr.responseJSON) // json格式,ajax请求使用该对象
}
});
}
init();//加载页面后直接调用init()函数servlet代码,需要用到fastjson库,将fastjson.jar放入到lib文件夹下
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//组装数据
Map map=new HashMap();
map.put("code", 1);
map.put("name", "小明");
map.put("age", 22);
map.put("性别", "男");
String str=JSON.toJSONString(map);//调用fastjson将map转换为json字符串
resp.setContentType( "text/html;charset=UTF-8 ");//设置编码集,否则中文会发生乱码
PrintWriter pw=resp.getWriter();
pw.println(str);//输出该json字符串
pw.flush();//清空缓冲区,立即输出
}web.xml中的配置
<servlet> <servlet-name>AjaxServlet</servlet-name> <servlet-class>com.douban.AjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxServlet</servlet-name> <url-pattern>/ajaxServlet</url-pattern> </servlet-mapping>