jQuery+struts+json

xiaoxiao2025-02-09  13

在struts中采用jquery利用json数据来动态无刷新更新页面。首先要准备一下基本知识,struts目前已经是展示层的业内标 准;jquery这里我们需要使用jquery的ajax方式获取后台数据;json是一种数据交换格式(不太清楚的可以看我之前的几篇文章《actionscript数据交互的几种类型》,《JSON简介》),项目构建工具maven。

主要讲一下的是jquery的ajax提交方式,我采用的是$.post方式:

jQuery.post( url, [data], [callback], [type] )

url        提交地址 data     提交的数据 callback 回调函数 type     数据类型,这里可以是xml,json,txt

实际代码:

123456789101112131415161718 //ajax提交 $.post(&quot;ajaxGetPersonBuildData.htm&quot;, str,function(data,textStatus){if(textStatus==&quot;success&quot;){for(var i=0;i&lt;$(data).length;i++){var str = $(data).get(i)[0].followUserEmpId; $(&quot;#&quot;+str+&quot;b1&quot;).html(&quot;·<a href="\&quot;#\&quot;">&quot;+$(data).get(i)[0].name+&quot;</a>&quot;); $(&quot;#&quot;+str+&quot;f1&quot;).html(&quot;·<span class="\&quot;black75\&quot;">&quot;+$(data).get(i)[0].areaage+&quot;M<sup>2</sup>&quot;+$(data).get(i)[0].room+&quot;&quot;+$(data).get(i)[0].drawingroom+&quot;&quot;+$(data).get(i)[0].price+&quot;</span>&quot;); $(&quot;#&quot;+str+&quot;b2&quot;).html(&quot;·<a href="\&quot;#\&quot;">&quot;+$(data).get(i)[1].name+&quot;</a>&quot;); $(&quot;#&quot;+str+&quot;f2&quot;).html(&quot;·<span class="\&quot;black75\&quot;">&quot;+$(data).get(i)[1].areaage+&quot;M<sup>2</sup>&quot;+$(data).get(i)[1].room+&quot;&quot;+$(data).get(i)[1].drawingroom+&quot;&quot;+$(data).get(i)[1].price+&quot;</span>&quot;); }}else{alert(&quot;error&quot;);}},&quot;json&quot;);

回调参数textStatus有以下几种返回要注意:

// textStatus can be one of: // &quot;timeout&quot; // &quot;error&quot; // &quot;notmodified&quot; // &quot;success&quot; // &quot;parsererror&quot;

接下去进入struts action中进行数据处理:

从request对象中取到的首先是一个字符串,我们要将他转为json对象再进行数据处理,完成之后返回的数据格式也应该是json对象给出response。

12345678910 response.setContentType(&quot;application/json;charset=gbk&quot;);PrintWriter out = response.getWriter();BufferedReader br =newBufferedReader(newInputStreamReader((ServletInputStream)request.getInputStream()));String line =null; StringBuilder sb =new StringBuilder();while((line = br.readLine())!=null){ sb.append(line);} log.info(&quot;Json Input:&quot;+sb.toString()); JSONObject jsonObj = JSONObject.fromObject(sb.toString());

注意最前面的response是进行编码指定的防止中文造成的乱码,获取到POST过来的数据之后通过JSONObject来转换对象,这里需要引入一个JSON包 (maven依赖)

<dependency> <groupid>net.sf.json-lib</groupid> <artifactid>json-lib</artifactid> <version>2.2.3</version> <classifier>jdk15</classifier> </dependency>

json-lib是一个专门提供java进行JSON格式操作的类包。序列化JAVA对象:

123456 JSONSerializer serializer =new JSONSerializer();try{ jarray.add(serializer.toJSON(building));}catch(JSONException e){ log.info(&quot;JSONException:&quot;+e.getMessage());}

转换JAVA对象到JSON的时候比较容易发生的异常在java对象的类型,因为是通过反射来转换对象的有些类型的字段转换时候会出一些异常,比如日期,长整型等。我的做法是将JAVA对象的字段都设为string。

相关资源:jquery的ajax传json对象数组到struts2的action
转载请注明原文地址: https://www.6miu.com/read-5024345.html

最新回复(0)