简体   繁体   中英

jQuery load 3 divs from single page

I am currently loading the same page 3 times with 3 different .load() calls. I am wanting to know if there is something I can do to optimize the code.

When I click a link currently it loads the page 3 times

$("#"+target).load(url + " #page", function(response, status, xhr){
  if(status === "error")
  {
    $("#"+target).load('error.php?error=503 #page', function(response, status, xhr){
      if(status === "error")
      {
        alert("Something has gone very wrong right now, please contact an admin quoting 'error.php'");
        return;
      }
    }); // This should never fail but if it does kill the page
    console.log('Content failed to load ' + xhr.status + ' ' + xhr.statusText);

    //Force update the title to error
    document.title = "Error";

    $("#pageBreadcrumbs").load('error.php #breadcrumbs');
  }
  else
  {
    console.log('Content was loaded');
    //Load the title dynamically
    document.title = "Venus | " + name;
    $("#pageBreadcrumbs").load(url + ' #breadcrumbs');

    if(sidebar === true)
      $("#pageSidebar").load(url + ' #sidebar');
  }

Is there anyway I can shorten this to just 1 call to the url or error page and extract it from there?

You can use this code:

$.get(url, function(response) {
    var $nodes = $(response);

    ... some conditions ...

    var $container1 = $("#"+target).html('');
    $nodes.find('#page').appendTo($container1);

    ... some conditions ...

    var $container2 = $("#pageBreadcrumbs").html('');
    $nodes.find('#breadcrumbs').appendTo($container2);
});

I'm not really sure that it works, but you can try it...

UPDATE

This code assumes that whole server response is wrapped in one container (div)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM