论坛首页 综合技术论坛

构建JSONP字符串

浏览 1998 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-09-21  

1.咱们需要一个这样的JSONP字符串

 var callbackP = "{\"msg\": 
[ 
\"<a href='#' target='_blank'><span class='notifyFn'>未受理<span class='notifyCount'>(50)</span></span></a>\", 
\"<a href='#' target='_blank'><span class='notifyFn'>已受理<span class='notifyCount'>(40)</span></span></a>\" 
] 
,\"success\":\"true\"}"

 

2:那么咱们先构建JSON字符串

import net.sf.json.JSONObject; 
JSONObject jsonObject = new JSONObject(); 
jsonObject.put("success", "false"); 
jsonObject.put("msg", new String[] { unviewdEqRemind, marketingRemind }); 
jsonObject.toString() 

 

3. 最后构建JSONP字符串

/** 
     * 构建JSONP需要的字符串,repalce做两件事 
     * 
     * 1:因为JSONObject会自动在字符/前加上\字符,所以需要用replace方法干掉它。 
     * 2:将JSON里的双引号加上转移字符\。 
     */
    private String buildJSONPString(String callback, JSONObject jsonObject) { 
        String resultData = new StringBuilder().append("var ").append(callback) 
                .append("=").append("\"").append( 
                        jsonObject.toString().replace("\\", "").replace("\"", 
                                "\\\"")).append("\"").append(";").toString(); 
        return resultData; 
    }
 

4. 在webx2.5中输出

  将构建完的JSONP字符串装入ActionResult里,如下。然后请求XX.do。

public ActionResult queryXpRemind( 
  ActionResult result = ActionResult.create(this); 
  result.setPlainText(jsonpString); 
  return result; 
} 

 




论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics