jbeduhai 发表于 2013-1-29 11:43:54

调用ajax返回json的另一种用法

1.页面代码
div id="commenthtml" style="display:none;">                <div class="form_box">                            <div class="form_row">                              <div class="form_label"><label>专辑名称:</label></div>                              <div class="form_field"><input type="text"id="albumName" name="albumName"value="" maxlength="30"/></div>                            </div>                            <div class="form_row">                              <div class="form_label"><label>描    述:</label></div>                              <div class="form_field"><textarea title="字数不超过200个字符" id="albumDesc" name="albumDesc" onKeyDown="LimitTextArea(this)" onKeyUp="LimitTextArea(this)" onkeypress="LimitTextArea(this)"></textarea></div>                            </div>                            <div class="form_row">                              <div class="form_label"></div>                              <div class="form_field">                                    <span class="btn_a"><input type="button" name="saveAlbum" id="saveAlbum"   value="创建"/></span>                                    <span class="btn_a"><input type="button" id="cancelBtn" value="取消"/></span>                              </div>                            </div>                </div></div>

调用ajax

function submitAlbum(form){    varalbumName = $("#albumName").val();    varalbumDesc = $("#albumDesc").val();   if(albumName == ""){      alert('提示:专辑不能为空!');      return false;   }   if(albumDesc == ""){      alert('提示:专辑描述不能为空!');      return false;   }   $.ajax({         type: "POST",         url: "/enterprisercenter/saveAlbum.action",         data: "tpId=1013&enterPriserAlbum.albumName=" + albumName +"&enterPriserAlbum.albumDesc=" + albumDesc,         dataType:'json',         success: function(json){         if (json.op=='succ'){         alert("操作成功");         window.location.reload();         }else if (json.op=='hasDiscard'){         alert(json.msg);         $("#" + json.code).focus();         }else{         alert(json.msg);         }         }      }); }


action 代码:
//保存相册    public void saveAlbum() throws IOException{      try {      if (FilterDiscard.hasDiscard(enterPriserAlbum.getAlbumName(),true)) {      getJsonHelper().fail("hasDiscard", "提示:名称中有非法字符!").set("code", "albumName").write();      return;      }      if (FilterDiscard.hasDiscard(enterPriserAlbum.getAlbumDesc(),true)) {      getJsonHelper().fail("hasDiscard", "提示:描述中有非法字符!").set("code", "albumDesc").write();      return;      }            enterPriserAlbum.setAlbumUserid(this.getSessionUser().getUserId()+"");            enterPriserAlbum.setCreateDate(DateTimeUtils.parseFullDateTime(DateTimeUtils.getDateTime()));            enterPriserAlbum.setUpdateDate(DateTimeUtils.parseFullDateTime(DateTimeUtils.getDateTime()));            enterPriserAlbum.setAlbumLogUrl("http://img1.woyopic.com/2010/0826/332/1-3bce7d978f54630889d0dd0310478dda.jpg");            enterPriserPhotoService.addEnterPriserAlbum(enterPriserAlbum);            getUser();            getJsonHelper().succ().write();      }catch(Exception ex) {      getJsonHelper().fail("操作失败!").write();            ex.printStackTrace();      }      //return "personalAlbum";            }

JsonHelper类代码:
import java.io.IOException;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.apache.struts2.ServletActionContext;/** * 输出的帮助类 作用:封装控制器中json的使用, 用法如下: * 基础功能 set("chargeType", "1"); //设置json的值 add("list", "value1"); //添加值 write(); * //输出 disableCache(); //清缓存 * 组合使用 set("chargeType", "1").set("count", 5).add("list", * "value1").add("list","value2").succ().write(); * 同时作注释 return getJsonHelper() //设置id .set("id", model.getId())    //设置 列表 * .set("list", configService.getList(model.getType())) // 设置 当前用户 * .set("userId", passportService.getCurrentUserId()) // 结果列表'list' .add("list", * "value1") .add("list","value2") // 清缓存 .disableCache().succ().write(); * @author*/public class JsonHelper {    private static final long serialVersionUID = -1531331734713947690L;    protected JSONObject root = new JSONObject(false);    /**   * 取得输出对象JSON(Dto)   *      * @return   */    public JSONObject getJson() {      return root;    }    /**   * 禁止缓存   * @return   */    public JsonHelper disableCache() {      HttpServletResponse res = ServletActionContext.getResponse();      res.setContentType("text/html;charset=UTF-8");//      res.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server//      res.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance//      res.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"//      res.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility      return this;    }    /**   * 设值   *      * @param key   * @param value   * @return   */    public JsonHelper set(String key, Object value) {      return put(key, value);    }    public JsonHelper put(String key, Object value) {      root.put(key, value);      return this;    }    /**   * 以数组形式在指定位置添加数据 即 JsonHelper() .add("list", "abc") .add("list", "bcd")   * .add("list", "cde");   *      * 等价于 JSONArray array = new JSONArray(); array.add("abc");   * array.add("bcd"); array.add("cde"); JsonHelper().set("list", array);   *      * 暂不支持子路径 即 add("max.list", "abc") 将会保存到   * JsonHelper().getJson().get("max.list") 而不是   * JsonHelper().getJson().get("max").get("list")   *      * @param key   * @param value   * @return   */    public JsonHelper add(String key, Object value) {      Object j = root.get(key);      if (j == null) {            root.put(key, new JSONArray());            j = root.get(key);      }      if (j instanceof JSONArray) {            ((JSONArray) j).add(value);            return this;      }      throw new RuntimeException("已经设值,且不是数组");    }    /**   * 快速设置成功页 效果 json.put("op", "succ");   *      * @return   */    public JsonHelper succ() {      root.put("op", "succ");      return this;    }    /**   * 快速设置失败页,由于‘不成功’就表示‘失败’,所以此方法一般不需调用, 除非需要指定失败类型(或提示语句)   *      * @param msg   * @return   */    public JsonHelper fail(String msg) {      root.remove("op");      root.put("msg", msg);      return this;    }    public JsonHelper fail(String op, String msg) {      root.put("op", op);      root.put("msg", msg);      return this;    }    /**   * 输出json,所用数据从json中取   *      * @return   */    public String write() {      HttpServletResponse res = ServletActionContext.getResponse();      res.setCharacterEncoding("UTF-8");//      res.setContentType("application/json");      try {            res.getWriter().print(root.toString());            return null;      } catch (IOException e) {            throw new RuntimeException("", e);      }    }    public String toString() {      return root.toString();    }}

struts.xml代码
<!-- 保存相册-->      <action name="saveAlbum" class="com.woyo.business.enterprisercenter.representation.action.EnterPriserAlbumAction" method="saveAlbum">            <interceptor-ref name="MastLoginWebStack"/><!--         <result name="personalAlbum" type="redirectAction">personalAlbum?tpId=1011</result>-->      </action>
页: [1]
查看完整版本: 调用ajax返回json的另一种用法