Problem with .load() in jquery
Ok, I'll put my code:
$("#html_contenido").load("../../jsp/comun/contenedor_operativa.html" ,function(){
$("#html_publicidad_reservar").load("../../html/pub/publicidad_reserva/publicidad_reservar_fr.html", function(){
alert($("#html_publicidad_reservar").html());
});
});
alert($("#html_publicidad_reservar").html());
The first alert shows what publicidad_reservar_fr.html()
has inside, but the second alert doesn开发者_StackOverflow中文版't show it, so in the webpage nothing appears inside #html_publicidad_reservar
Can anyone tell me what's wrong with this code?
The second alert executes while the AsynchronousJAX is still running. So the element is still empty. If you need to run code after it has been loaded, do it in your inner callback where the first alert is located.
second alert
run before the first one because load
function make Ajax
call then run the its call back function so the scenario is
- Load function
- second alert
- Finish Load
- run callback
you can check this
.load
uses ajax, which by default is asynchronous, so the first alert
shows it AFTER the html loads, while the second alert runs before the first alert and at that time, nothing is .load
ed yet.
Timeline is this:
- Javascript reads the
.load
and executes it. - The second
alert
fires because.load
from #1 is still happening contenedor_operativa.html
is loaded.- Since #3 happened and it has loaded, the next
.load
happens - After the nested
.load
happens, the first alert in the source code happens
What this means is, that you should put your code inside of where the first alert
in the source code is, otherwise you're operating on non-loaded elements.
You can do asynch:false
but that kills the whole purpose of using XHR/"Ajax"
精彩评论