我怎样才能让 jsonp 与我的班级融洽相处?
整个 jsonp 的事情非常令人困惑...
这就是我想做的:
- 我有一个类
DataRetriever
- 该类有一个方法
GetData
GetData
使用以下代码发出 jsonp 请求:var new_tag = document.createElement('script'); new_tag.type = '文本/javascript'; new_tag.src = 'http://somesite.com/somemethod?somedata'; // 添加元素 var bodyRef = document.getElementsByTagName("body").item(0); bodyRef.appendChild(new_tag);
现在,来自服务器 somesite.com
的 jsonp 数据可以调用我的代码中的函数与数据。问题是,数据如何传递到请求它的 DataRetriever 实例?
我真的被困在这里了。
This whole jsonp thing is quite confusing...
Here is what I want to do:
- I have a class
DataRetriever
- The class has a method
GetData
GetData
makes a jsonp request with the following code:var new_tag = document.createElement('script'); new_tag.type = 'text/javascript'; new_tag.src = 'http://somesite.com/somemethod?somedata'; // Add the element var bodyRef = document.getElementsByTagName("body").item(0); bodyRef.appendChild(new_tag);
Now, the jsonp data from the server somesite.com
can call a function in my code with the data. The problem is, how does the data get delivered to the instance of DataRetriever
that requested it?
I'm really stuck here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
jQuery 提出的解决方案是提供一个像这样的匿名回调函数:
我认为这也可以适应您的情况。
如果您不想提供匿名函数,则可以在 GetData 函数的幕后执行相同的操作。
请注意,您必须确保 JSONP 请求接受回调 GET 参数。如果您使用第三方 API,他们已经支持这一点。希望这有帮助!
The solution jQuery came up with, is to provide an anonymous callback function like this:
I think this could be adapted to your case as well.
You could do the same thing behind the scenes in the GetData function if you didn't want to provide an anonymous function.
Note you will have to make sure the JSONP request accepts the callback GET parameter. If you're using a 3rd party API they will already support this. Hope this helps!