Getting trouble with jquery load()

87 Views Asked by At

In some parts of my web application I've ajax login mechanism, after successful login I'm updating topbar using following code instead of refreshing the page.

$("#top-bar").load($(location).attr('href'));

Above line of code updating topbar without any issue, but in some pages I've openlayers maps there, page structure is totally destructing due to above line. Because I'm using jQuery tabs on same page.

After searching I came to know that some special characters in the script may cause these type of issues. So its difficult to find which line of code is causing this issue, finally I'm using below line to update the topbar.

$("#top-bar").load($(location).attr('href')+' #top-bar');

This line of code is working without any issues, as a developer I want to know what is difference between above two calls ?

Edit

There is even issue with my first call, I was not observed the destructed part of the page. After reading answers I've clearly observed the page. Anyhow second call is the perfect one for me. Sorry for giving trouble by asking this type question, thanks for everyone who contributing for this question.

3

There are 3 best solutions below

0
On

The first example is loading the entire HTML contents of the external page in the href and inserting everything:

$("#top-bar").load($(location).attr('href'));

The second example is loading the entire HTML contents of href, but only inserting the #top-bar from that page rather than the entire document:

$("#top-bar").load($(location).attr('href')+' #top-bar');

.load() API docs

0
On

For a better understanding I changed the IDs a little bit:

$("#top-bar").load($(location).attr('href'));

This one loads the full content of the link and appends it to the #top-bar

$("#top-bar").load($(location).attr('href')+' body');

This one only loads the body of the link and appends it to the #top bar.

I assume that it is working in both scenarios because you have a #top-bar in your loaded document.

0
On

From the official documentation:

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:

Here, any JavaScript loaded into #a as a part of the document will successfully execute.

$( "#a" ).load( "article.html" );

However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

$( "#b" ).load( "article.html #target" );

I think this was exactly what you are looking for.