零碎 通过json传输数据

每篇一语:不用追求最好的,只须追求适合的!

1.需要用到的json包

2.服务端处理json

3.jQuery处理json

 

======================  华丽丽的分割线  ======================

 

1.需要用到的包

 

  但是需要特别注意的是,因为json大量引用了Apache commons的包,所以这里要一并加入(否则会有异常)。需要的commons包共4个,除了commons的包外,还需要引入一个ezmorph.jar包,所以使用json一共要多引入7个包,分别如下:

  json-lib.jar

  jsonplugin.jar;

  commons-collections.jar;

  commons-lang.jar

  commons-beanutils.jar

  commons-logging.jar

  ezmorph.jar;

 

======================  华丽丽的分割线  ======================

 

2.服务端处理json

 

 1 import net.sf.json.JSONObject;
2 public class TestAction extends ActionSupport {
3
4 public void isUsernameRepeated(){
5 // new一个json,可以很方便的传输键值对给jQuery
6 JSONObject json = new JSONObject();
7
8 // 这里加入逻辑处理语句
9 // 略......
10
11 // 加入键值对
12 json.put("status","success");
13
14 // 将json传输出去
15 PrintWriter out = null;
16 try {
17 // out = ServletActionContext.getResponse().getWriter();
18 out = MyServletContext.getResponse().getWriter();
19 } catch (IOException e) {
20 e.printStackTrace();
21 }finally {
22 out.println(json);
23 out.flush();
24 out.close();
25 }
26 }
27
28
29 }

 

======================  华丽丽的分割线  ======================

 

3.jQuery处理json

 

 1 function jsonTest() {
2 /* 这里编写逻辑代码 */
3
4 /* 顺便写一下jQuery的ajax方法的注释 */
5
6 /* 在这里使用jQuery的ajax方法,所以记得在页面引入jquery的包 */
7 $.ajax({
8 /* type:指明要传输的方式,GET 或 POST */
9 type : "POST",
10 /* url:要访问的地址,在SSH中,一般指明某个action */
11 url : "TestJson",
12 /* 要带的参数,可以有多个,当多个的时候,写法和地址栏的一样 */
13 data : "attrTest=" + attrTest,
14 /* ajax访问成功则执行success */
15 success : function(data) {
16 var json;
17 try{
18 /* 解析json类型 */
19 json = $.parseJSON(data);
20 if(json.status == "true") {
21 /* 接收到该时的状态逻辑语句 */
22                     } /* 若还有其他接收到的类型,则继续判断,此处略 */  
23 }catch(e) {
24 /* 若出现异常的处理语句 */
25                 }
26 },
27 error : function(XMLHttpRequest, textStatus, errorThrown) {
28 /* 若ajax访问失败的处理语句 */
29        }
30 });
31 }

posted on 2011-09-20 18:33  五月十七  阅读(419)  评论(0编辑  收藏  举报

导航