jQuery的Ajax实现异步传输List、Map
由于项目需要通过ajax得到后台的List对象里面的值,由于没有接触过json所以前期我只能先传字符串再在js里截取子串实现。闲暇时间摸索了一下关于json接受List对象的方法,步骤如下:
1.首先下载json所以依赖的包, Json-lib 最新版 json-lib-2.3-jdk15.jar,其官方网站是:http://json-lib.sourceforge.net/可以直接download,细心的你会发现其网站页面里面有提示它还需要其他包:
Json-lib requires (at least) the following dependencies in your classpath:
jakarta commons-lang 2.4
jakarta commons-beanutils 1.7.0
jakarta commons-collections 3.2
jakarta commons-logging 1.1.1
ezmorph 1.0.6
其中一般项目中都会有前4个,所以只需要下载ezmorph 1.0.6 就可以了
下载地址分别是:
http://commons.apache.org/lang/
http://commons.apache.org/beanutils/
http://commons.apache.org/collections/
http://commons.apache.org/logging/
http://ezmorph.sourceforge.net/
2.首先先见一个小web项目
先建一个User类:
package com.json;
public class User {
String username;
String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
再建一个servlet
package com.json;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
public class TestJson extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String str= request.getParameter("name");//得到ajax传递过来的paramater
System.out.print(str);
PrintWriter out = response.getWriter();
List list = new ArrayList();//传递List
Map m=new HashMap();//传递Map
User u1=new User();
u1.setUsername("zah");
u1.setPassword("123");
User u2=new User();
u2.setUsername("ztf");
u2.setPassword("456");
list.add(u1); //添加User对象
list.add(u2); //添加User对象
m.put("u1", u1);
m.put("u2", u2);
JSONArray jsonArray2 = JSONArray.fromObject( list );//转化成json对象
JSONObject jo=JSONObject.fromObject(m);//转化Map对象
out.print(jsonArray2);//返给ajax请求
out.print(jo);//返给ajax请求
}
}
配置好web.xml中的servlet映射,这一步就略了。
3.建立ajax实现
这里为了快速实现用的是jquery实现的。
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function test(){
$.ajax({
type:"POST", //请求方式