通过 jQuery/AJAX 抓取外部 URL 的 HTML
我需要通过 jQuery/AJAX 从外部 URL 获取特定的 DOM 元素(按 ID)。我知道这违反了同源策略,但是当我专门获取 HTML(而不是 JSON)时,我找不到可接受的解决方法。
举例来说,我在 website1.com,我需要抓取并输出 website2.com 的 #something 元素的内容。我怎样才能使用 jQuery 做到这一点?
编辑:似乎是 为什么不能的重复我从 jQuery 加载方法加载外部资源? 这有一个很好的答案。
I need to grab a specific DOM element (by ID) from an external URL via jQuery/AJAX. I know that this violates the same origin policy, but I can't find an acceptable workaround for when I'm specifically grabbing HTML (instead of JSON).
So say for example, I'm on website1.com, and I need to grab and output the contents of the #something element of website2.com. How can I do this using jQuery?
EDIT: Seems to be a duplicate of Why cant I load an external resource from jQuery load method? which has a good answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(回答我自己的问题):
请注意,由于同源策略,这在浏览器中是不可能的。为了解决这个问题(就像佩卡在上面的评论中所说的那样),您通常会创建所需内容的本地代理。因此,如果您正在 website.com 上工作,并且需要获取 google.com 的一部分,您可以创建 website.com/google ,它只是通过一些服务器端代码克隆 google.com 。然后您就可以自由地做任何您想做的事情,因为它在您的域中。
我遇到的问题是我正在开发一个 BlackBerry WebWorks 项目,这意味着我仅限于 HTML/CSS/JS,而且我实际上并没有在网站上工作,所以代理是不可能的。幸运的是,WebWorks 允许您向您创建的每个应用程序添加受信任的域,这意味着同源策略不适用于这些域。
(Answering my own question):
Note that this is impossible in the browser because of the same origin policy. To get around it (like Pekka said in the comments above), you'd normally create a local proxy of the desired content. So like if you are working on website.com, and you need to grab a part of google.com, you could create website.com/google which would just be a clone of google.com via some server side code. Then you'd be free to do whatever you wanted to it, since it's on your domain.
The catch I was dealing with is that I was working on a BlackBerry WebWorks project, which means that I'm limited to HTML/CSS/JS, and I'm not actually on a website, so a proxy is impossible. Luckily, WebWorks lets you add trusted domains to each app you create, which means that the same origin policy doesn't apply to those domains.
错误的。只要服务器支持 JSONP,该策略就不是绝对的。 Google JSONP Jquery,您将看到大量工作示例在执行您想要的操作:通过 ajax 从您自己以外的域返回 Web 服务数据。
False. The policy is not absolute as long as the server supports JSONP. Google JSONP Jquery and you'll see tons of working examples doing what you want: returning webservice data from a domain other than your own via ajax.