views:

276

answers:

2

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("...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>
+1  A: 

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
}
DisgruntledGoat
I added the whole code, how can i add the test of that elem to that another div? Thank you in advance
l1x
I assumed from your other comment that the page *is* on another domain, so I've updated my answer with a workaround, and how to use the content you get back.
DisgruntledGoat
+3  A: 

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

jitter
Thank you as well. I have just noticed that it XSS is not supported by ajax :))))
l1x