jQuery加载外部站点页面 [英] jQuery load external site page
本文介绍了jQuery加载外部站点页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以从外部网站加载单个页面?
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);
}
});
我们将不胜感激
推荐答案
您遇到了跨域策略问题,原因是AJAX(出于安全原因)不允许您从页面中获取内容不在同一域上.
You're running into a cross domain policy issue cause AJAX (for security reasons) will not let you grab content from a page that does not sit on the same domain.
要摆脱它并完成任务:
您需要一个PHP文件,您可以仅使用以下PHP行来调用grabber.php
:
<?php echo file_get_contents($_GET['url']); ?>
比起您的html文件(或其他文件,就像:)
Than inside your html (or whatever file just do like:)
<!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?
- 现在,AJAX正在向
grabber.php
页面发送一个简单的GET请求,
-
grabber.php
回显所需的内容
- 现在内容在您的(服务器)域中了!
- AJAX很高兴为您服务:)
- now, AJAX is sending a simple GET request to the
grabber.php
page, grabber.php
echoes the desired content- now the content is on your (server) domain!
- and AJAX is happy to serve you :)
这篇关于jQuery加载外部站点页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文