jQuery 加载外部站点页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14999573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:11:41  来源:igfitidea点击:

jQuery load external site page

jqueryload

提问by ngplayground

Is it possible to load a single page from an external website?

是否可以从外部网站加载单个页面?

I am trying to show up a single page but cannot seem to get it to work

我试图显示一个页面,但似乎无法让它工作

$("#response").load("http://domain.com", function(response, status, xhr) {
   if (status == "error") {
      var msg = "Sorry but there was an error: ";
      alert(msg + xhr.status + " " + xhr.statusText);
   }
 });

Help would be greatly appreciated

帮助将不胜感激

回答by Roko C. Buljan

You're running into a cross domain policyissue cause AJAX (for security reasons) will not let you grab content from a page that does not sit on the same domain.

您遇到了跨域策略问题,因为 AJAX(出于安全原因)不会让您从不在同一域中的页面抓取内容。

To get rid of it and accomplish your task:
you need a PHP file you can call grabber.phpwith just this line of PHP:

为了摆脱它并完成你的任务:
你需要一个 PHP 文件,你可以grabber.php用这行 PHP调用:

<?php echo file_get_contents($_GET['url']); ?>

Than inside your html (or whatever file just do like:)

比在你的 html (或任何文件只是这样做:)

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <meta charset=utf-8 />
    <title>test</title>
</head>
<body>

    <div id="response"></div>

</body>

<script>
$(function(){
    var contentURI= 'http://domain.com #element';    // URL TO GRAB + # of any desired element // if needed :)
    $('#response').load('grabber.php?url='+ contentURI);
});
</script>

</html>

Why does this work?

为什么这样做?

  • now, AJAX is sending a simple GET request to the grabber.phppage,
  • grabber.phpechoes the desired content
  • now the content is on your (server) domain!
  • and AJAX is happy to serve you :)
  • 现在,AJAX 正在向grabber.php页面发送一个简单的 GET 请求,
  • grabber.php呼应想要的内容
  • 现在内容在您的(服务器)域中!
  • AJAX 很高兴为您服务 :)

回答by andri

Are you trying to load a page on a different domain?

您是否正在尝试加载不同域上的页面?

If yes, then it seems you got a cross-domain policy on your way...

如果是,那么您似乎有一个跨域策略......