发送JSONP与JSON数据? [英] Sending JSONP vs. JSON data?

查看:126
本文介绍了发送JSONP与JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个需要以JSONP格式返回数据的Web服务。我正在使用JSON taglib用于JSP,我认为所有必须添加的都是括号,但我找不到一个好的资源来验证这一点。

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.

例如,使用此函数返回Web服务函数:

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

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

这是正确的吗?

谢谢!

推荐答案

JSONP只是一个允许网络应用跨域检索数据的黑客攻击。可以说它违反了同源政策(SOP)。它的工作方式是使用Javascript在页面中插入script元素。因此,您需要一个回调函数。如果你没有,你的Javascript将无法访问JSON对象。但是通过使用JSONP,您的Javascript代码可以调用回调函数。

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

这篇关于发送JSONP与JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆