我必须做什么才能规避 JSON 的 JavaScript 同源策略...这也适用于 XML 数据吗?

发布于 2024-10-08 20:47:06 字数 174 浏览 1 评论 0原文

我对同源策略有疑问...

我有使用 JSON 和 XML 数据的 JavaScript 代码。我知道我需要将 JSON 更改为 JSONP,因为我的服务器位于不同的域中,但我只在客户端执行此操作吗?那么 XML 数据呢?也可以以某种方式跨域加载吗?

最后,有没有什么好的网站可以通过示例深入解释这一点?

I have question about the same origin policy...

I have JavaScript code using JSON and XML data. I know I need to change JSON to JSONP, since my server is on a different domain, but do I only do that in the client side? And what about the XML data? Can that also be loaded cross-domain somehow?

Finally, are there any good websites explaining this in-depth, with examples?

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

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

发布评论

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

评论(3

○闲身 2024-10-15 20:47:06

在 jsonp 响应中对 XML 进行编码,然后让客户端提取它并将其解释为 XML。

Encode your XML inside your jsonp response, and then make your client extract it and interpret it as XML.

草莓酥 2024-10-15 20:47:06

您确实必须修改服务器。您可以将 JSONP 的原理用于 XML。您只需传递一个字符串:

例如假设您的服务器端程序位于 /xmlp 。您传递一个回调参数,然后脚本将 XML 输出包装在其中。

例如

/xmlp?callback=mycall

输出:

mycall('<root><el attr="value"/ ></root>');

然后您可以在客户端解析 XML(传递到 JavaScript mycall 函数中)。

You do have to modify the server. You can use JSONP's principle for XML. You just have to pass a string:

E.g. assume your server-side program is at /xmlp . You pass a callback parameter, then the script wraps the XML output in this.

E.g.

/xmlp?callback=mycall

outputs:

mycall('<root><el attr="value"/ ></root>');

You then parse the XML (passed into a JavaScript mycall function) on the client side.

别想她 2024-10-15 20:47:06

一旦您的数据源位于不同的域中,您就必须使用 JSONP 来获取数据。这适用于 JSON 和 XML 数据。 JSONP 只是一种表示法,它使您可以提供回调函数,并且一旦远程调用完成就会调用它。数据作为回调参数提供。

当然,您的 API 必须支持 JSONP,只要对 API 的请求包含“?callback=f”,它就必须返回类似

{ f(data); }

f 的内容 - 是在页面某处定义的函数。

所以,基本上当 API 调用完成后,你就会调用回调函数。

使用来自不同来源的 API

  1. 您有多种选择通过 YQL - http://developer.yahoo.com/yql/< /a>
  2. 手动、纯 JS 或使用 jQuery - http://www.beletsky.net/2010/07/json-jsonp-and-same-origin-policy-issue.html

As soon as you datasource is in different domain, you have to use JSONP to get data. This is both for JSON and XML data. JSONP is just a notatation, that makes you available to supply a callback function and it would be called as soon as remote call finished. Data is provided as callback parameter.

Of cause, you API must support JSONP, as soon as request to API contains "?callback=f", it must return something like

{ f(data); }

and f - is function defined somewhere on your page.

So, basically as API call finished, you call back function is called.

You have several options to use API from different origin

  1. With YQL - http://developer.yahoo.com/yql/
  2. Manually, pure JS or with jQuery - http://www.beletsky.net/2010/07/json-jsonp-and-same-origin-policy-issue.html
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文