Sending JSONP vs. JSON data?

落花浮王杯 提交于 2019-12-17 11:50:05

问题


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!


回答1:


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) + ")";
}



回答2:


I added one example to address Cross Domain JSONP ( Json with padding ) with Jquery and Servlet or JAX-WS webservice.

Please check this article.
http://reddymails.blogspot.com/2012/05/solving-cross-domain-problem-using.html



来源:https://stackoverflow.com/questions/4683114/sending-jsonp-vs-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!