2012-08-29 78 views
4

我編碼了以下內容以將JSON數據發送到前端。但是,由於跨域安全問題,我們需要將其轉換爲JSONP,有人可以建議我需要修改此轉換嗎?如何把JSON轉換成JSONP?

服務器端代碼

JsonFactory jfactory = new JsonFactory(); 
     ObjectMapper mapper = new ObjectMapper(); 
     try { 
       StringWriter stringWriter = new StringWriter(); 
       JsonGenerator jGenerator = jfactory.createJsonGenerator(stringWriter); 
       jGenerator.useDefaultPrettyPrinter(); 
       jGenerator.writeStartObject(); // { 
       jGenerator.writeStringField("title", title); // "title" : title 
       jGenerator.writeStringField("Description", desc); // "desc" : 
       jGenerator.writeFieldName("images"); 
       jGenerator.writeStartArray(); // [ 
       if(imageArray.size() != 0){ 
       for (String img : imageArray) { 
        jGenerator.writeString(img); // "msg 1" 
       } 
       } 
       jGenerator.writeEndArray(); // ] 
       jGenerator.writeEndObject(); // } 
       jGenerator.close(); 
       response.getWriter().write(stringWriter.toString()); 
       System.out.println(stringWriter.toString()); 
       response.getWriter().close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      System.out.println("JasonGen servlet called end"); 

前端的Javascript:

$.getJSON("http://localhost:8080/JsoupPrj/JasonGen?url="+ url[0],function(data){ 
       var imageArray=[]; 
       var imageOne = null; 
        imageArray=data.images; 
.................... 
} 
+0

你知道JSON和JSONP有什麼區別嗎? –

+0

另一個帖子有很好的解釋:http://stackoverflow.com/questions/5350924/how-enable-jsonp-in-resteasy – 2012-10-04 18:38:01

回答

4

由於您使用jQuery和你控制的服務器端,改變你的服務器代碼,以便它看起來對callback參數。此參數的值將是客戶端代碼所期望的回調函數的名稱。然後,不要返回裸露的JSON,而應將其返回爲:callbackName(rawJson)

例如,假設一個servlet API:

String callbackName = request.getParameter("callback"); 

// ... your JSON code 

if (callbackName != null) 
{ 
    // JSONP wrapping: 
    response.getWriter().write(callbackName + 
           "(" + stringWriter.toString() + ")"); 
    System.out.println(callbackName + "(" + stringWriter.toString() + ")"); 
} 
else 
{ 
    response.getWriter().write(stringWriter.toString()); 
    System.out.println(stringWriter.toString()); 
} 

response.getWriter().close(); 

然後在客戶端,繼續使用jQuery.getJSON,但?callback=?查詢參數附加到URL,或改用jQuery.ajax您的垂詢,並使用dataType: jsonp設置。

+0

+1爲好的解釋:) – Nav