js的Ajax的POST请求和servlet的json响应的交互

来源:互联网 发布:第一次爬泰山必知 编辑:程序博客网 时间:2024/06/10 21:41

ajaxTest3.jsp的页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'ajax1.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><script type="text/javascript">//定义XMLHttpRequest对象function jsAjaxPost(){  if(window.XMLHttpRequest){var xmlhttprequest = new XMLHttpRequest();xmlhttprequest.open('POST','./servlet/ajaxTest3');//请求方式xmlhttprequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//请求头xmlhttprequest.onreadystatechange=function (){if(xmlhttprequest.readyState===4&&xmlhttprequest.status===200){//alert("rh--"+xmlhttprequest.getResponseHeader("Content-Type"));var type=xmlhttprequest.getResponseHeader("Content-Type");//响应头包含json是json响应if(type.indexOf("json")!=-1){var ul = document.getElementById("jsajaxpost");  ul.innerHTML += "<li>status:" + xmlhttprequest.status + "</li>";   var xmlDoc=xmlhttprequest.responseText; //alert("1---"+xmlDoc); var data=eval(xmlDoc); //因为用data instanceof Array得到的是false,但可以当数组用 //所以认为eval将json格式的string值转成类数组对象// alert(data);// alert(data.length);// alert("1---"+typeof(data));// alert("2---"+data instanceof Array);                             ul.innerHTML += "<li>return:" +"userName:"+data[0].userName + "userId:"+data[0].userId+"</li>";                            ul.innerHTML += "<li>return:" +"userName:"+data[1].userName + "userId:"+data[1].userId+ "</li>"; }}};xmlhttprequest.send("user=我1&com=a2");}}</script>  </head>    <body>  <ul><li><a href="javascript:jsAjaxPost();">(POST)javascript ajax testing.</a><ul id="jsajaxpost"></ul></li></ul>  </body></html>

ajaxTest3.java的代码,这里用了产生的json对象的jar包,包含json-lib-2.2.3-jdk15.jar,ezmorph-1.0.6.jar,

commons-beanutils-1.8.0.jar,commons-collections-3.1.jar,commons-lang-2.5.jar,commons-logging-1.1.3.jar:

/** *  */package ajax1;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;/** * @author Administrator * */public class ajaxTest3 extends HttpServlet {/** * Constructor of the object. */public ajaxTest3() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { doPost(request,response);}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("application/json"); ArrayList<UserModel> list=new ArrayList<UserModel>(); UserModel user1=new UserModel();//用户对象1        user1.setUserId("1");         user1.setUserName("张三");        user1.setUserSex("男");         list.add(user1);                  UserModel user2=new UserModel();//用户对象2         user2.setUserId("2");         user2.setUserName("李四");         user2.setUserSex("女");         list.add(user2);  JSONArray json=JSONArray.fromObject(list);System.out.println(json.toString());//控制台打印:[{"userId":"1","userName":"张三","userSex":"男"},{"userId":"2","userName":"李四","userSex":"女"}]response.setCharacterEncoding("UTF-8");PrintWriter out = response.getWriter();out.print(json.toString());out.flush();out.close();}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}
访问的网址:http://localhost:8088/ajaxWeb/ajax3.jsp,点击超链接得到:




0 0
原创粉丝点击