Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

java - Sending JSONP vs. JSON data?

I am making a web service that needs to return data in JSONP format. I am using the JSON taglib for JSP, and I thought all that had to be added were parenthesis, but I cannot find a good resource which verifies this.

For example, ever web service function returns using this function:

private static String getJSONPObject(String s) throws JSONException {
    return "(" + new JSONObject(s) + ")";
}

Is this correct?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JSONP is simply a hack to allow web apps to retrieve data across domains. It could be said that it violates the Same Origin Policy (SOP). The way it works is by using Javascript to insert a "script" element into your page. Therefore, you need a callback function. If you didn't have one, your Javascript would have no way to access the JSON object. But by using JSONP, your Javascript code can call the callback function.

So you must specify the callback name. So your function might look like this:

private static String getJSONPObject(String callback, String s) throws JSONException {
    return callback + "(" + new JSONObject(s) + ")";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...