开发者

how can i get dom elements from html using jQuery's ajax method?

I have encountered a unique problem. I am doing a simple ajax call using jQuery to get the contents of an html file.

$.ajax({
  url: "foo.html",
  dataType: "html",
  success: function(data){
    console.log(data);
  }
});

foo.html is a simple html file with a main div called #mainContainer. All I want to do is get all of the contents from the mainContainer and store them in a var so i can add them to another div somewhere in my page.

Here's index.ht开发者_如何学编程ml (the file that is making the call).

Here's foo.html (the file i am trying to call and parse).


The jQuery ".load()" API does exactly what you're asking for:

$('#the_target_div').load("foo.html #mainContent", function() {
  // stuff to do when content is ready
});

You simply add a selector string after the URL, separated by a space.

One thing to note: if the loaded page has any important JavaScript in it (in <script> tags), when you load the page that way the scripts will not be run. If you need that behavior, then you either have to pull out the content yourself (which is a minor mess) or else have your server do the work and respond with only the fragment you need.

A completely different approach would be to load your page into a hidden <iframe> and then dive into that DOM to find what you want. It could then be copied into the main page.


var mainContainerInnerHtml = $(data).find("#mainContainer).html();


you do not need get the dom elements. you can use query replaceWith function to replace.

just like this:

$("#data").replaceWith($("#data",ajaxReturnHtml)).serialize();

it works to me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜