samedi 1 août 2015

jQuery returns undefined while filtering AJAX reponse

I'm attempting to figure out AJAX in jQuery and am trying to extract the contents of one element on the page and inject it into another. Here's a test scenario I've been playing around with:

1st page:

...
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="script.js"></script>
</head>
<body>
    <button>Load it!</button>
    <div class="content"></div>
...

2nd page:

...
<div class="container">
    <h1>Hello World!</h1>
    <div class="text">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui nulla impedit a nostrum eos voluptas, quidem cum, consequatur suscipit voluptate officia sapiente laboriosam similique dignissimos praesentium obcaecati, nemo commodi, laborum!</p>
    </div>  
</div>
...

script file from 1st page:

$(function(){
    $('button').on('click', function(){
        $.ajax({
            url: "ajax/index.html"
        }).done(function(response){
            $('.content').html($(response).find('.container').html());
        });
    });
});

Several posts on stack exchange like this one and this one have indicated that this is the direction I should be going in to grab 1 element's HTML from another page using AJAX. However, upon running the code on the first page, the contents from .container are not returned, and passing those jQuery methods to console.log() as so (console.log($(response).find('.container').html());) returns undefined to the console. What's wrong here?

Also, yes, I realize that using .load() is an option here, but I'd really like to learn how to use the AJAX method for jQuery as I believe it gives the programmer more find-tuned control.

Aucun commentaire:

Enregistrer un commentaire