我編碼了以下內容以將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;
....................
}
你知道JSON和JSONP有什麼區別嗎? –
另一個帖子有很好的解釋:http://stackoverflow.com/questions/5350924/how-enable-jsonp-in-resteasy – 2012-10-04 18:38:01