javascript 如何设置 JSONP?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9519209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:57:15  来源:igfitidea点击:

How do I set up JSONP?

javascriptjsonfirefox-addonjsonp

提问by Jacques Blom

What do I need to on the server side to allow someone to get data from that server using JSONP. And what do I need to do on the user side as well? I want to use JSONP as an alternative to an XMLHttpRequest.

我需要在服务器端做什么才能允许某人使用 JSONP 从该服务器获取数据。我还需要在用户方面做什么?我想使用 JSONP 作为 XMLHttpRequest 的替代方案。

It won't work out of my Firefox extension, because of the same-origin policy. So, people recommended JSON, but I am pretty lost after searching for tutorials and guides on the internet.

由于同源策略,它在我的 Firefox 扩展中不起作用。所以,人们推荐了 JSON,但在互联网上搜索教程和指南后,我很迷茫。

Thanks for the help!

谢谢您的帮助!

采纳答案by marko

Assuming your server is running PHP, you just need to add 'callback' GET request.

假设您的服务器正在运行 PHP,您只需要添加“回调”GET 请求。

<?php header('content-type: application/json; charset=utf-8');
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
echo $_GET['callback'] . '('.json_encode($data).')';

And on client side (using jQuery):

在客户端(使用 jQuery):

$.ajax({url: 'http://site.com/data.php', dataType:'jsonp'});

The PHP code above is just for demo, don't forget to sanitise$_GET['callback']

上面的 PHP 代码仅用于演示,不要忘记清理$_GET['callback']

That said, if your issue just the same origin policy, you'll probably just need to allow cross-originfrom the server side, and everything should work.

也就是说,如果您的问题只是同源策略,您可能只需要允许服务器端的跨域,一切都应该正常工作。

回答by T.J. Crowder

On the server side, all you have to set up is a web resource (e.g., page) that accepts a GETrequest and returns the data using the JSON-P convention, which is:

在服务器端,您只需要设置一个接受GET请求并使用 JSON-P 约定返回数据的 Web 资源(例如,页面),即:

callback({"data": "here"});

...where the function name ("callback" in that example) is usually taken from one of the query string parameters (by convention, the parameter "callback"), and the data is JSONtext (although technically it could be anything that's valid in a JavaScript object literaly, the convention with JSON-P is to restrict yourself to what's valid in JSON). So for instance, let's say that the request looked like this:

...其中函数名称(该示例中的“回调”)通常取自查询字符串参数之一(按照惯例,参数“回调”),并且数据是JSON文本(尽管从技术上讲,它可以是任何在 JavaScript 对象中有效,JSON-P 的约定是将自己限制在 JSON 中有效的内容)。例如,假设请求如下所示:

http://example.com/foo.php?callback=bar

That calls the page foo.php(doesn't have to be PHP, can be anydynamic server-side system), telling it that the function we want it to call is "bar". Our response would be:

调用页面foo.php(不必是 PHP,可以是任何动态服务器端系统),告诉它我们希望它调用的函数是“bar”。我们的回应是:

bar({"data": "here"});

On the client side, you have to add a scriptelement to the page dynamically, and also add the callback function that will get triggered by the JSON-P response. Usually you want to give that function some random name, and remove it when you're done.

在客户端,您必须script动态地向页面添加一个元素,并添加将由 JSON-P 响应触发的回调函数。通常你想给这个函数一些随机名称,并在你完成后删除它。

Here's a complete exampleas an answer to another question here on Stack Overflow. You may have to adapt it slightly for use in a Firefox add-on, but the concepts are the same.

这是一个完整的示例,作为对 Stack Overflow 上另一个问题的回答。为了在 Firefox 附加组件中使用,您可能需要稍微调整它,但概念是相同的。

回答by Marc B

jsonp is json with a wrapper, so you can fake ajax requests to another server by dynamically inserting new <script>tags, with src's pointing at the other server. The wrapper essentially makes the jsonp return stuff be a valid javascript function call that can be executed to extract the standard json data within.

jsonp 是带有包装器的 json,因此您可以通过动态插入新<script>标签来伪造对另一台服务器的 ajax 请求,其中 src 指向另一台服务器。包装器本质上使 jsonp 返回的东西成为一个有效的 javascript 函数调用,可以执行它来提取其中的标准 json 数据。

Generally, in an insecure 'just to demo' version, you'd have something like this:

通常,在一个不安全的“只是为了演示”版本中,你会有这样的东西:

function unwrap_jsonp(data) {
    eval(data);
}

The remote server would return the following literal text:

远程服务器将返回以下文字文本:

unwrap_json("{'this':'is','sparta':'!'}");

Note that this is literal Javascript plaintext code, which is executed and "unwraps" the embedded JSON string back to a native javascript data structure.

请注意,这是文字 Javascript 纯文本代码,它被执行并将嵌入的 JSON 字符串“解包”回原生 javascript 数据结构。

Most JSONP services allow specifying an extra parameter via the query string to name the handler function you want to wrap the response in, e.g.

大多数 JSONP 服务允许通过查询字符串指定一个额外的参数来命名你想要包装响应的处理函数,例如

http://example.com/getjsonp.php?callback=unwrap_json