开发者

Problem with .load() in jquery

开发者 https://www.devze.com 2023-03-17 13:55 出处:网络
Ok, I\'ll put my code: $(\"#html_contenido\").load(\"../../jsp/comun/contenedor_operativa.html\" ,function(){

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

  1. Load function
  2. second alert
  3. Finish Load
  4. 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 .loaded yet.

Timeline is this:

  1. Javascript reads the .load and executes it.
  2. The second alert fires because .load from #1 is still happening
  3. contenedor_operativa.html is loaded.
  4. Since #3 happened and it has loaded, the next .load happens
  5. 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"

0

精彩评论

暂无评论...
验证码 换一张
取 消