how to get content of nested div with jQuery
So I have a nested div structure and I would like to get the content of the second level. How should i do it with jQuery .load? The following works only with simple divs(non-nested)...
.load("https://remote-site.com/blah.html #div_1", function() { }
Ok, the whole stuff is:
<html>
<head>
<title>AJAX Checker </title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script src="jquery.js" language="javascript" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#loadData").click(function() {
$(this).text开发者_JS百科("...One Moment Please...");
$("#container").append('<div id="favoriteMovies"></div>')
.children("#favoriteMovies").hide()
.load("https://remote-site/blah.html", function() {
var elem = $(this).find('#subject');
$("#loadData").remove();
$("#favoriteMovies").slideDown("slow");
});
return false;
});
});
</script>
</head>
<body>
<div id="container">
<a href="#" id="loadData">Click</a>
</div>
</body>
</html>
Assuming the 2nd level div has and id
.load("https://yoursite.com/blah.html #div_1 #2ndlevel_div", function() { }
Else change selector accordingly like you would normally (e.g. first child div of #div_1
)
.load("https://yoursite.com/blah.html #div_1 > div:first", function() { }
BTW.: Note this will only work for your own page (cross-domain requests are not supported with ajax
Firstly, loading data with AJAX will only work if the page is on the same domain. "remote site" indicates you're trying to get stuff from a different domain.
What you can do to get round this is have a server-side script that fetches the content and returns it. In PHP you'd want to use the cURL functions (there are plenty of questions here about that sort of thing, just do a search with your chosen language).
// `getpage.php` would be your script that fetches the URL provided
.load("http://yoursite.com/getpage.php?url=https://remote-site.com/blah.html #div_1", function() {
// `$(this)` should contain the div you selected
$('#loadData').html( $(this) ); // replace `loadData` with whatever div you wanna store the content in
}
精彩评论