How to use AJAX loading with Bootstrap tabs?

后端 未结 10 1642
無奈伤痛
無奈伤痛 2020-12-02 08:30

I used bootstrap-tabs.js and it has worked perfectly.

But I didn\'t find information about how to load content through AJAX request.

So, how to use AJAX load

10条回答
  •  天涯浪人
    2020-12-02 09:05

    Here is how I do it. I utilize an attribute data-href which holds the url I want to load on show. This will not reload data that is already loaded unless you set $('#tab').data('loaded'); to 0 or remove it. It also handles relative vs. absolute urls by detecting the location of the first slash. I am not sure of the compatibility with all browsers but it works in our situation and allows for the functionality we are looking for.

    Javascript:

    //Ajax tabs
    $('.nav-tabs a[data-href][data-toggle="tab"]').on('show', function(e) {
      var $this = $(this);
      if ($this.data('loaded') != 1)
      {
        var firstSlash = $this.attr('data-href').indexOf('/');
        var url = '';
        if (firstSlash !== 0)
          url = window.location.href + '/' + $this.attr('data-href');
        else
          url = $this.attr('data-href');
        //Load the page
    
        $($this.attr('href')).load(url, function(data) {
          $this.data('loaded', 1);
        });
      }
    });
    

    HTML:

    This content isn't used, but instead replaced with contents of tab1.php.

    You can put a loader image in here if you want

提交回复
热议问题