jsp+jquery+json

客户端的js脚本

采用jquery.js

Urlpath为访问网址

     $.getJSON(urlPath,

         function callback(json){

              var len = json.length;

              //alert("asdfasdf" + json.id);

              //alert(len);

              //alert(json[0].username);

              for(i = 0;i < len;i++) {

                   alert(json[i].username);

              }

             

          }

     );  

服务器端:

方法1jsp中使用json相关的包

引入json相关的jar

Person类有id,username,value属性

Ajax请求的jsp页面源码为

<%@ page language="java" pageEncoding="GB18030"%>

<%@page import="bean.Person"%>

<%@page import="java.util.List"%>

<%@page import="java.util.ArrayList"%>

 

<%

List<Person> list = new ArrayList<Person>();

 

Person p1 = new Person();

p1.setId(1);

p1.setUsername("name1");

p1.setValue("student1");

list.add(p1);

 

Person p2 = new Person();

p2.setId(2);

p2.setUsername("name2");

p2.setValue("student2");

list.add(p2);

 

 

net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(list);

//JSONObject jo = new JSONObject();

response.setCharacterEncoding("utf-8");   //转码.不然很难看.

//{"id":1,"username":"何镇镇1","value":"student1"}

response.getWriter().print(jsonArray);

System.out.println(jsonArray);

//打印出来的格式为[{"id":1,"username":"name1","value":"student1"},{"id":2,"username":"name2","value":"student2"}]

%>

 

方法2直接构造json格式的数据

 

response.setCharacterEncoding("utf-8");   //转码.不然很难看.

response.getWriter().print("[{'id':1,'username':'张思','value':'student1'},{'id':1,'username':'张思','value':'student1'}]");

posted @ 2012-08-30 15:11  坏混混  阅读(277)  评论(0编辑  收藏  举报