I use $.ajax()
to get some HTML pages from my server.
The retrun contains the full HTML result. But i am only interested in a very specific div inside this document.
The only give开发者_JAVA技巧n thing is that my ajax success function returns a JSON object. I have made a PHP proxy file i use for other stuff that returns me a JSON object with the headers, some information to the file I'm loading and its contents. So basically i have a string containing the whole HTML of the page.
Actually i make it like that: $($(data.content)[21])
but this is awful example of jquery (Because i use the $ selector twice, and the HTML could by changing and the div I'm interested in could be changing position in the jquery array). I would like to get only the div <div id="items">...</div>
and its contents and only then select it with jquery.
What is the best practice for this case? What would your approach look like?
PS: in case that my example is not clear, your can see an example here: http://meodai.ch/content_slider/
success: function(result) {
var div = $(result).filter('#items');
}
Try this:
var $items = $(data.content).find('#items')
or if #items
is at the top level of the <body>
, then do this instead:
var $items = $(data.content).filter('#items')
- http://api.jquery.com/find/
- http://api.jquery.com/filter/
Once you parse the JSON response and get the HTML out of it, wrap it in a jQuery object:
var $j = $(htmlGoesHere);
Then, extract the HTML of the div:
var itemsHTML = $j.find("#items").html();
精彩评论