使用javascript加载跨域内容
好的,问题来了:
远程站点需要从其他域拉取复杂的 html 页面内容。 iframe解决方案不够好,因为确定页面高度的问题,并且IE浏览器上不允许跨域ajax。有 JSONP,但需要提供的代码量太复杂,我们还需要提供一些功能。
解决方案:
在服务器端,我们动态生成 javascript,其中包含字符串变量中的所有复杂 html 内容。在远程端,我们只包含对此脚本的调用,然后在页面上放置一个。然后用服务变量的内容填充 Div。它可以在所有浏览器上跨域工作,并且内容显示完美:))。
问题:
这种方法有什么问题?为什么网上没有提到这样的解决方案?它似乎非常适合提供任何类型的小部件和类似内容,但现在我担心其中存在一些很大的谬误:)?
请揭穿它:)
Ok, here's the problem:
The remote site needs to pull complex html page content from other domain. Iframe solution is not good enough because of the problem with determining the page height, and cross domain ajax is not allowed on IE browsers. There is JSONP but amount of code that needs to be served is too complex and we also need to serve some funcionalities.
The solution:
On server side we are dinamically generating javascript that contains all the complex html content in a string variable. On remote side we just include call to this script and we put a on the page. Div is then filled with content from served variable. It works cross domain on ALL browsers and the content displays perfectly :)).
The question:
What's wrong with this approach? Why there is no mention of such solution anywhere online? It seems perfect for serving any kind of widgets and alike content, and now I'm affraid there is some big fallacy in it:)?
Please debunk it :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这种做法没有问题。出于安全考虑,客户端禁止跨域,但在服务器端您可以按照自己的意愿进行。
这里的区别在于,您必须重新加载页面才能查询其他域,然后将其推送到您的页面。所以基本上你可以执行以下操作:
1-你的 javascript 对它自己的域执行 ajax 请求。
2-在服务器端,您发出跨域请求
3- 打印一些 js/html 供请求者使用
在这种情况下,您比直接在客户端执行多了一个请求。
There is no problem with this approach. Cross domain is forbidden on client side for security matters, but on server side you do as you wish.
The difference here is that you have to reload a page in order for it to query the other domain and then push it to your page. So basically you could do the following :
1- Your javascript does an ajax request to it's own domain.
2- On the server side, you make a cross domain request
3- You print some js/html to be used by the requester
In that scenario, you have one more request than doing it directly on the client side.
正如 Pointy 所评论的,这本质上与 JSONP 相同。请记住,大多数浏览器都会阻止向第 3 方网站发送 cookie。
As Pointy commented, this is essentially the same as JSONP. Keep in mind that most browsers block sending cookies to the 3rd party site though.
只要服务器发送 access-control-allow-origin 响应头,就可以跨域。请参阅链接文章的示例
http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html
Cross domain is possible as long as the server sends an access-control-allow-origin response header. See the linked article for an example
http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html