How to use AJAX loading with Bootstrap tabs?

后端 未结 10 1587
無奈伤痛
無奈伤痛 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:15

    I wanted to load fully dynamic php pages into the tabs through Ajax. For example, I wanted to have $_GET values in the links, based on which tab it was - this is useful if your tabs are dynamic, based on database data for example. Couldn't find anything that worked with it but I did manage to write some jQuery that actually works and does what I'm looking for. I'm a complete jQuery noob but here's how I did it.

    1. I created a new 'data-toggle' option called tabajax (instead of just tab), this allows me to seperate what's ajax and what's static content.
    2. I created a jQuery snippet that runs based on that data-toggle, it doesn't mess with the original code.

    I can now load say url.php?value=x into my Bootstrap Tabs.

    Feel free to use it if you want to, code is below

    jQuery code:

    $('[data-toggle="tabajax"]').click(function(e) {
        e.preventDefault()
        var loadurl = $(this).attr('href')
        var targ = $(this).attr('data-target')
        $.get(loadurl, function(data) {
            $(targ).html(data)
    
        });
        $(this).tab('show')
    });
    

    HTML:

  • Val 1
  • So here you can see that I've changed the way bootstrap loads thing, I use the href for the dynamic ajaxlink and then add a 'data-target' value to the link instead, that should be your target div (tab-content).

    So in your tab content section, you should then create an empty div called val1 for this example.

    Empty Div (target):

    Hope this is useful to someone :)

提交回复
热议问题