?核心:?前端通过jsonp跨域调用后端接口,接口返回的json必须支持callback回调函数
代码如下:
1、前端jquery
var searchUrl ="${some_url}/tieba/queryTiebaThread4Admin.action"; $.ajax(searchUrl, { data: {‘tiebaId‘: tiebaId,‘threadId‘: threadId}, dataType: ‘jsonp‘, type : "get", jsonpCallback:"callback", jsonp: "callback", cache : false, crossDomain: true, success: function(result) { if(result && result.resultCode == 0){ $("#first_post_id").val(result.data.firstPost); $("#title").val(result.data.title); showTips(‘数据搜索有结果‘,"success"); }else{ $("#first_post_id").val(‘‘); $("#title").val(‘‘); showTips(‘未抓取主题帖数据,请检查主题和帖吧ID是否正确‘,"error"); } }, error:function(e){ $("#first_post_id").val(‘‘); $("#title").val(‘‘); showTips(‘未抓取主题帖数据,请稍后重试‘,"error"); } });
2、后端controller
public Render queryTiebaThread4Admin(@Read(key = "tiebaId") Long tiebaId, @Read(key = "threadId") Long threadId, @Read(key = "callback") String callback) { TiebaResult<Map<String,Object>> result = new TiebaResult<Map<String,Object>>(); Map<String,Object> dataMap = new HashMap<String, Object>(); try { AnchorTieba tiebaInfo = tiebaQueryManager.getTieba(tiebaId); AnchorTiebaThread tiebaThread = threadQueryManager.queryThread(tiebaId, threadId); if(tiebaInfo != null && tiebaThread != null){ dataMap.put("tiebaId",tiebaId); dataMap.put("threadId",threadId); dataMap.put("tiebaName",tiebaInfo.getName()); dataMap.put("firstPost",tiebaThread.getFirstPost()); dataMap.put("title",tiebaThread.getTitle()); result.setData(dataMap); }else{ result.setResultCode(ErrorCode.NOT_FOUND); } } catch (Exception e) { result.setResultCode(ErrorCode.NOT_FOUND); logger.info("queryTiebaThread4Admin:", e); } StringBuilder resultBuilder = new StringBuilder(JSONObject.fromObject(result).toString()); if(StringUtils.isNotBlank(callback)){ resultBuilder.insert(0, ‘(‘).insert(0,callback).append(‘)‘); } return new Render(RenderType.TEXT, resultBuilder.toString()); }
原文:http://my.oschina.net/caiz/blog/512915