jquery ajax servlet交互

来源:互联网 发布:手机上如何改淘宝评价 编辑:程序博客网 时间:2024/06/06 09:33

jquery ajax servlet交互,所需的java包 jackson-all-1.9.2.jar、json-lib-2.4.jar、commons-lang-2.0.jar、ezmorph-1.0.6.jar、commons-beanutils.jar、commons-collections-3.2.1.jar...  两个js    jquery1.4.js、json2.js

如何ajax出现textStatus :406错误,很可能就是包忘记加了!

上代码

servlet:

package com.sunshine.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.*;

public class JasonServlet extends HttpServlet {

/**
  * Constructor of the object.
  */
public JasonServlet() {
  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 {
  PrintWriter out = response.getWriter();
  List<UserModel> list = new ArrayList<UserModel>();
  UserModel um = new UserModel();
  um.setId("1");
  um.setUsername("sss");
  um.setAge(222);
  list.add(um);
  Map<String, Object> modelMap = new HashMap<String, Object>(3);
  modelMap.put("total", "1");
  modelMap.put("data", list);
  modelMap.put("success", "true");
  JSONArray nn = JSONArray.fromObject(modelMap);
  out.print(nn);// 返给ajax请求
}

/**
  * 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 {
  try {
   String userStr = readJSONString(request);// 得到requestContext
   JSONObject jsonObj = JSONObject.fromObject(userStr);// 转换成JSONObject
   System.out.println(jsonObj.getInt("id"));// 得到JSONObject的userId值
   System.out.println(jsonObj.getString("username"));
   System.out.println(jsonObj.getString("age"));
  
   JSONObject resultJSON = new JSONObject();// 构建一个JSONObject
   resultJSON.accumulate("errNum", 1);
   resultJSON.accumulate("errInfo", "成功");

   response.setContentType("application/x-json");// 需要设置ContentType为"application/x-json"
   PrintWriter out = response.getWriter();
   out.println(resultJSON.toString());// 向客户端输出JSONObject字符串
   out.flush();
   out.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

}

/**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException
  *             if an error occurs
  */
public void init() throws ServletException {
  // Put your code here
}

public String readJSONString(HttpServletRequest request) {
  StringBuffer json = new StringBuffer();
  String line = null;
  try {
   BufferedReader reader = request.getReader();
   while ((line = reader.readLine()) != null) {
    json.append(line);
   }
  } catch (Exception e) {
   System.out.println(e.toString());
  }
  return json.toString();
}

}

js:

$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
  if (o[this.name]) {
   if (!o[this.name].push) {
    o[this.name] = [ o[this.name] ];
   }
   o[this.name].push(this.value || '');
  } else {
   o[this.name] = this.value || '';
  }
});
return o;
};

$(document).ready(
  function() {
   jQuery.ajax( {
    type : 'GET',
    url : 'jasonServlet',
    dataType: 'json',   //返回值类型
    success : function(data) {
    //if (data && data.success == "true") {
    if (data) {
    alert(data);
    $.each(data, function(i, item) {
     $('#info').html("共" + item.total + "条数据。<br/>"+item.success+"<br/>");
     // $.each(data.data, function(i, item) {
     $.each(item.data, function(i, item) {
       $('#info').append(
         "编号:" + item.id + ",姓名:" + item.username
           + ",年龄:" + item.age);
      });
     });
    
     }
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest.status);
                        alert(XMLHttpRequest.readyState);
                        alert(textStatus);
                    }
   });
   $("#submit").click(function() {
    var jsonuserinfo = $.toJSON($('#form').serializeObject());
    alert(jsonuserinfo);
    jQuery.ajax( {
     type : 'POST',
     contentType : 'application/json',
     url : 'http://localhost:8081/spring_ajax/jasonServlet',
     data : jsonuserinfo,
     dataType : 'json',
     success : function(data) {
      alert("新增成功!");
     },
     error : function(data) {
      alert("error")
     }
    });
   });
  });

html:

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring MVC</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/index.js"></script>
</head>
<body>
<div id="info"></div>
<form action="add" method="post" id="form">
id:<input type="text" name="id"/>
name:<input type="text" name="username"/>
age:<input type="text" name="age"/>

<input type="button" value="提交" id="submit"/>
</form>
</body>
</html>

<input type="button" value="提交" id="submit"/>
</form>
</body>
</html>