我编写了以下代码,用于向前端发送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;
....................
}