action中json的應用

y_keven發表於2014-04-24

      這篇文章重點介紹action中json資料的返回處理;如果需要看前端程式碼的一些特效或ajax的json接收,請看上一篇部落格:http://blog.csdn.net/yangkai_hudong/article/details/24422817

1.需要依賴的方法

 /**

    * 獲取PrintWriter

    *

    * @throws IOException

    */

    public static PrintWritergetPrintWriter(HttpServletResponse response) throws IOException {

       response.setContentType("text/plain;charset=utf-8");

       response.setCharacterEncoding("UTF-8");

       response.setHeader("Pragma", "no-cache");

       response.setHeader("Cache-Control", "no-cache");

       response.setDateHeader("Expires", 0);

       PrintWriter out = response.getWriter();

       return out;

    }

 

    /**

    * 輸出json操作

    *

    * @param out

    *            PrintWriter

    * @param result

    */

    public voidresponseStr(PrintWriter out, String result) {

       out.println(result);

       out.flush();

       out.close();

    }

 

    public String createJsonObject(Stringflag, String msg) {

       JSONObject obj = new JSONObject();

       try {

           obj.put("flag", flag);

           obj.put("msg", msg);

       } catch (JSONException e) {

           logger.error("生成JSON格式出錯" + e);

           obj.put("flag", "0");

           obj.put("msg", "由於網路問題,資料處理失敗");

       } finally {

            return obj.toString();

       }

}

 

2.action中的使用案例

    public ActionForwardadd(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws IOException,AppException {

       PrintWriter out = getPrintWriter(response);

       String docTitle = Tool.getDefaultValue(request, "docTitle", "");

       String uid = Tool.getDefaultValue(request, "uid", "");

       try {

           Long flag1 = WeiboWidgetDao.add(docTitle, uid);

           Long flag2 = WeiboWidgetDao.addRel(docTitle, uid);

           if (flag1 != null && flag2 != null) {

                responseStr(out, createJsonObject("1", "新增成功!"));

                WeiboWidgetDao.updateCache("doc", docTitle); // 更新詞條快取

           } else {

                responseStr(out, createJsonObject("0", "新增詞條微博失敗!"));

           }

       } catch (Exception e) {

           logger.debug("新增詞條微博失敗:" + e);

           responseStr(out,createJsonObject("0", "新增詞條微博失敗,發生異常!"));

       }

       return null;

    }

 

3.js中的使用案例

 

儲存

function save() {

       // 儲存前驗證

       var docTitle = $("#win_docTitle").val();

       var uid = $("#win_uid").val();

       if (docTitle != "" && uid != "") {

              $.ajax({

                     dataType: 'json',

                     type: 'POST',

                     url: '/weiboWidget.do',

                     data: {

                            'action' : $("#win_action").val(),

                            'id' : $("#win_id").val(),

                            'docTitle' : $("#win_docTitle").val(),

                            'uid' : $("#win_uid").val(),

                     },

                     success : function(data) {

                            if (data.flag == 1) {

                                   alert(data.msg);

                                   window.location.href= "/weiboWidget.do?action=show";

                            }else {

                                   alert(data.msg);

                            }

                            return false;

                     },

                     error: function() {

                            alert("由於網路問題,儲存資料失敗!");

                            return false;

                     }

              });

       }else {

              alert("詞條名和微博UID不能為空!");

              return false;

       }

}

 

刪除

 

/**

 * 批量刪除操作

 *

 */

function deleteData() {

       var idList =document.getElementsByName("id_list");

       var ids = "";

       var docTitles = "";

       // 檢查是否選擇內容

       for (i = 0; i < idList.length;i++) {

              if(idList[i].checked) {

                     var temp =idList[i].value.split(";");

                     ids+= temp[0] + ",";

                     docTitles+= temp[1] + ",";

              }

       }

       if (ids == "") {

              alert("請選擇紀錄!");

       }else {

              $.post("/weiboWidget.do?action=delete&" + new Date(), {

                     'ids' : ids,

                     'docTitles' : docTitles

              },function(data) {

                     window.location.href= "/weiboWidget.do?action=show";

                     return false;

              });

       }

}


轉載請指明:http://blog.csdn.net/yangkai_hudong

相關文章