標籤:cat 構造 注意 utf-8 string result 設定 color except
http://hw1287789687.iteye.com/blog/2188617
java web中如何跨域請求呢?
使用jsonp,詳情請參考:http://json-p.org/
頁面代碼如下:
Html代碼
- <!DOCTYPE html>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title></title>
- <script type="application/javascript" >
- function jsonpCallback(result) {
- alert(JSON.stringify(result));
- /*for(var i in result) {
- alert(i+":"+result[i]);//迴圈輸出a:1,b:2,etc.
- } */
- }
- var JSONP=document.createElement("script");
- JSONP.type="text/javascript";
- JSONP.src="http://192.168.0.100:8080/tv_mobile/video/text2?callback=jsonpCallback";
- document.getElementsByTagName("head")[0].appendChild(JSONP);
- </script>
- </head>
- <body>
-
- </body>
- </html>
在瀏覽器中訪問的效果:
後台採用spring mvc:
Java代碼
- @ResponseBody
- @RequestMapping(value = "/text2",produces=SystemHWUtil.RESPONSE_CONTENTTYPE_JAVASCRIPT2 )
- public String text2(HttpServletRequest request, HttpServletResponse response,String contentType2,String callback)
- throws IOException {
- String content = null;
- Map map = new HashMap();
-
- map.put("fileName", "a.txt");
- content=JSONPUtil.getJsonP(map, callback);
- System.out.println(content);
- return content;
-
- }
JSONPUtil.getJsonP 靜態方法的實現如下:
Java代碼
- /***
- * 用於jsonp調用
- * @param map : 用於構造json資料
- * @param callback : 回調的javascript方法名
- * @return
- */
- public static String getJsonP(Map map,String callback)
- {
- ObjectMapper mapper = new ObjectMapper();
- String content = null;
- try {
- content = mapper.writeValueAsString(map);
- System.out.println(content);
- } catch (JsonGenerationException e) {
- e.printStackTrace();
- } catch (JsonMappingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if(ValueWidget.isNullOrEmpty(callback)){
- return content;
- }
- return callback+"("+content+")";
- }
依賴jackson 庫
後台返回的內容是:jsonpCallback({"fileName":"a.txt"})
content type是
注意:後台返回的形式是:函數名(參數),此處的函數名就是回呼函數的名稱
參考:
spring mvc設定應答體的content type
AJAX 跨域請求 - JSONP擷取JSON資料:http://justcoding.iteye.com/blog/1366102
App Framework發送JSONP請求(3):http://hw1287789687.iteye.com/blog/2190719
java web get請求跨域(轉)