Malork Malork - 2 months ago 7
Javascript Question

Ajax .load retrieves what from server

It is a simple doubt:
When we use something like

$('#content').load( "page.php #content");
, it loads the entire
page.php
"in server-side" and then extract
#content
element or it loads only the specified element?

Beyond that, is this
$('#content').load( "page.php #content");
the same as this:

$.ajax({
url:"page.php",
type:'GET',
error: function(){
alert("Oops!"); // Em caso de o AJAX dar erro (opcional)
},
success:
function(data){
$('#content').html($(data).find('#content').html());
}
});


When it comes to "method to get from the server"?

Answer

Yes, those would be the same, XMLHttpRequest can not load partial pages.
jQuery splits the url and the given selector, and then loads the entire page based on the url, and then just extracts the given element(s) based on the passed in selector as a filter using find().

Here's a shortened (somewhat modified) version of jQuery's load(), just to show how it works

function(url, params, callback) {
    var selector, div, html, self = this;

    // if the url param contains a space, get the selector to use as filter
    if ( url.indexOf(" ") > -1 ) { 
        selector = jQuery.trim(url.slice( url.indexOf(" ") ));
        url = url.slice(0, url.indexOf(" "));
    }

    // make regular ajax call
    jQuery.ajax({
        url      : url,
        type     : "GET",
        dataType : "html",
        data     : params
    }).done(function(responseText) {
        div  = jQuery('<div>');
        html = jQuery.parseHTML(responseText);

        self.html(  div.append( html ).find(selector) );
    });

    return this;
}