客户端或服务器端需要进行哪些更改才能使 getJSON() 工作?
我正在使用一些已经创建的 Web 服务,我需要使用 ajax 调用它们。我正在开发的网站托管在与 Web 服务不同的域中。我现在意识到这会导致同源策略出现问题。
我试图根据文章使用 JSON 来解决它:
以及此处的大量其他问题。
我尝试过以下代码(用“webservice”替换实际域):
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("http://webservice/restserver.aspx?",
{
method: "userInfo",
userID: "039304303930302",
sessionID: "STRING",
format: "json"
},
function(data) {
alert("GET Returned");
});
});
</script>
1)这是否有什么严重错误,因为我是 JSON 和 AJAX 的新手
2)Web 服务是否需要有一个回调,例如“&”回调=?”添加到它
3)是否有任何其他方法来解决跨域调用
任何建议或帮助将非常受欢迎,因为我已经为此工作了很长时间。
谢谢!
I'm working with some web services that have already been created and I need to call them using ajax. The site I'm working on is hosted in a different domain than that of the web services. I'm now aware of the problems this causes with the same-origin policy.
I'm trying to get round it using JSON, based on articles:
and tonnes of other questions on here.
I have tried the following code (replaced actual domain with "webservice"):
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("http://webservice/restserver.aspx?",
{
method: "userInfo",
userID: "039304303930302",
sessionID: "STRING",
format: "json"
},
function(data) {
alert("GET Returned");
});
});
</script>
1) Is there anything terribly wrong with this as I'm new to JSON and AJAX
2) Does the web service need to have a callback e.g.- "&callback=?" added to it
3) Is there any other way to get around cross-domain calls
Any suggestions or help will be most welcome as I have working on this for ages.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要与 JSON 不同的 JSONP。您需要修改 Web 服务方法,以便它可以接受附加参数(例如
callback=foo
),并将 JSON 响应包装在此函数中:此外,为了实现跨域 AJAX 调用,jQuery 使用隐藏
标记,因此必须将 Web 服务配置为接受 GET 请求。
$.getJSON()
方法文档包含使用 Flickr 的示例您可以尝试运行并使用 FireBug 查看确切的请求/响应。您可以在此处查看它的实际效果。You need JSONP which is different than JSON. You need to modify the web service method so that it can take an additional argument (for example
callback=foo
) and would wrap the JSON response in this function:Also to implement cross domain AJAX calls jQuery uses a hidden
<script>
tag so the web service must be configured to accept GET requests.The
$.getJSON()
method documentation contains an example using Flickr which you could try running and looking at the exact request/response with FireBug. You may see it in action here.