为 json 数据构建 jsonp 包装器

发布于 2024-07-26 15:02:01 字数 481 浏览 0 评论 0原文

我已经尝试解决这个问题很长时间了,现在知道为什么这是不可能的。 网址

http://twittercounter.com/api/?username= Anand_Dasgupta&output=json&results=3

返回一个 json,但是当我附加一个“&callback=get”时,它没有指定回调包装函数。

所以现在唯一的解决方案是手动构建一个围绕 json 数据的包装器。

我的问题是我该怎么做。 php/javascript 中是否已经存在一些代码,我可以根据我的规格进行更改。

任何建议将被认真考虑。

谢谢

阿南德

Ive been tryin to solve this for a long time and now know why its not possible.
The url

http://twittercounter.com/api/?username=Anand_Dasgupta&output=json&results=3

returns a json but when i append a "&callback=get" along with it,it doesnt specify the callback wrapper function.

So the only solution now is to build a wrapper manually round the json data.

My question is how do i do that.
Is there some code already existing in php/javascript that i can change according to my specs.

Any advice will be appreciated.

Thank You

Anand

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴者 2024-08-02 15:02:01

JSONP 的目的是将 JSON(将在客户端被评估为 JavaScript)包装到只有请求数据的客户端知道的回调中。 这可以防止客户端执行不需要的 JavaScript 代码。 如果没有回调,您将遇到同源策略问题(JSONP 解决了这个问题),因此您只能请求脚本来自的 URL。

基本上,您必须使用 PHP 附加回调,即在服务器端使用代理脚本。 该脚本从另一个 URL 检索数据并将其包装到回调中:

<?php
    // Don't know on the fly how to request data from another URL in PHP, but it's easy to find out
    $response = request_url('http://twittercounter.com/api/?username=Anand%5FDasgupta&output=json&results=3');
    echo $_GET['callback'] . '(' . $response . ')';
?>

Well the purpose of JSONP is to wrap the JSON (which will be evaluated as JavaScript on the client side) into a callback that only the client requesting the data knows. This prevents the client from executing unwanted JavaScript code. Without the callback ou will have the same origin policy problem (which JSONP solves), so you can only request tot he URL the script came from.

Basically you will have to attach the callback with PHP, meaning on the server side, with a proxy script. The script retrieves the data from the other URL and wraps it into a callback:

<?php
    // Don't know on the fly how to request data from another URL in PHP, but it's easy to find out
    $response = request_url('http://twittercounter.com/api/?username=Anand%5FDasgupta&output=json&results=3');
    echo $_GET['callback'] . '(' . $response . ')';
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文