是否可以从外部网站加载单个页面?
我试图显示一个页面,但似乎无法让它工作
$("#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);
}
});
Run Code Online (Sandbox Code Playgroud)
非常感谢帮助
Rok*_*jan 23
您遇到了跨域策略问题,因为AJAX(出于安全原因)不允许您从不在同一域中的页面中获取内容.
要摆脱它并完成你的任务:
你需要一个PHP文件,你可以grabber.php用这行PHP 调用:
<?php echo file_get_contents($_GET['url']); ?>
Run Code Online (Sandbox Code Playgroud)
比你的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>
Run Code Online (Sandbox Code Playgroud)
为什么这样做?
grabber.php页面发送一个简单的GET请求,grabber.php 回应所需的内容