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
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.
To get rid of it and accomplish your task:
you need a PHP file you can call grabber.php with just this line of PHP:
<?php echo file_get_contents($_GET['url']); ?>
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?
- 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 :)
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...
来源:https://stackoverflow.com/questions/14999573/jquery-load-external-site-page