简体   繁体   中英

Get portion of page HTML via AJAX

I am trying to get everything inside a div with the id "ajax_container" via AJAX. The AJAX response contains all the page HTML, but when I use the selector to isolate the contents of the div, it returns undefined.

 $(".ajax-click").click(function(e){
     $.ajax({
         url: $(this).attr("href"),
         success: function(response) {
           alert(response);
           var html = $('#ajax_container', response).html();
           alert(html);
         }
     });
 e.preventDefault();
 });

HTML trying to be selected:

<html>
<body>
    <div id="ajax_container">
        <p>Content here</p>
    </div>
</body>
</html>

If you're just trying to get a snippet of a page, I'd suggest using .load https://api.jquery.com/load/

$( "#target" ).load( "ajax/test.html #ajax_container" );

In the code snippet above, you're loading a page named test.html , but just retrieving the element with the ID of #ajax_container .

So your snippet would look something like:

$(".ajax-click").click(function(e){
     // get the element clicked
     var $clickedElement = $(this),
          pageToLoad = $clickedElement.prop("href");


     $( "#ajax_container" ).load( "ajax/test.html " + pageToLoad );

     e.preventDefault();
 });

It seems like you're trying to implement client side routing. If you're trying to replace a container with ajax content then you should use a library that will help you achieve this. A solid library to use is Path.js. Below is a link with a small example and it is similar to what you want to acheive.

http://www.javascriptoo.com/path-js

You need .load() to do that

$("#TargetID").load("ajax/test.html #ajax_container");
                 //^^URL            ^^ element you want to load

$('#ajax_container', response).html();

is equal to

$('#ajax_container').find(response).html();

There is no element with id ajax_container so it return undefined

With your current function, you should use .html() in order to set the html string to the element.

For example

 $(".ajax-click").click(function(e){
     $.ajax({
         url: $(this).attr("href"),
         success: function(response) {
           $('#ajax_container').load(response);
           alert("Success");
         }
     });
 e.preventDefault();
 });

See https://api.jquery.com/html/

However, as others have said .load() works too. ( https://api.jquery.com/html/ )

 $(".ajax-click").click(function(e){
     $('#ajax_container').load($(this).attr("href"), function() {
         alert("Load successful.");
     });
 e.preventDefault();
 });

I would recommend using .load() over .html() as the former is cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM