如何在 Bootstrap 选项卡中使用 AJAX 加载?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8456974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 11:05:35  来源:igfitidea点击:

How to use AJAX loading with Bootstrap tabs?

ajaxtwitter-bootstrap

提问by assaqqaf

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

我使用了 bootstrap-tabs.js,它工作得很好。

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

但是我没有找到有关如何通过 AJAX 请求加载内容的信息。

So, how to use AJAX loading with bootstrap-tabs.js?

那么,如何在 bootstrap-tabs.js 中使用 AJAX 加载?

采纳答案by ukessi

You can listen the changeevent and ajax load content in the event handler

您可以change在事件处理程序中监听事件和ajax加载内容

$('.tabs').bind('change', function (e) {
    var now_tab = e.target // activated tab

    // get the div's id
    var divid = $(now_tab).attr('href').substr(1);

    $.getJSON('xxx.php').success(function(data){
        $("#"+divid).text(data.msg);
    });
})

回答by Owen

In Bootstrap 2.0 and up you have to bind to the 'show' event instead.

在 Bootstrap 2.0 及更高版本中,您必须改为绑定到 'show' 事件。

Here's an example HTML and JavaScript:

下面是一个 HTML 和 JavaScript 示例:

<div class="tabbable">
    <ul class="nav nav-tabs" id="myTabs">    
        <li><a href="#home"  class="active" data-toggle="tab">Home</a></li>
        <li><a href="#foo" data-toggle="tab">Foo</a></li>
        <li><a href="#bar" data-toggle="tab">Bar</li>
    </ul>
    <div>
        <div class="tab-pane active" id="home"></div>
        <div class="tab-pane" id="foo"></div>
        <div class="tab-pane" id="bar"></div>
    </div>
</div>

JavaScript:

JavaScript:

$(function() {
    var baseURL = 'http://yourdomain.com/ajax/';
    //load content for first tab and initialize
    $('#home').load(baseURL+'home', function() {
        $('#myTab').tab(); //initialize tabs
    });    
    $('#myTab').bind('show', function(e) {    
       var pattern=/#.+/gi //use regex to get anchor(==selector)
       var contentID = e.target.toString().match(pattern)[0]; //get anchor         
       //load content for selected tab
       $(contentID).load(baseURL+contentID.replace('#',''), function(){
            $('#myTab').tab(); //reinitialize tabs
       });
    });
});

I wrote a post about it here: http://www.mightywebdeveloper.com/coding/bootstrap-2-tabs-jquery-ajax-load-content/

我在这里写了一篇关于它的帖子:http: //www.mightywebdeveloper.com/coding/bootstrap-2-tabs-jquery-ajax-load-content/

回答by user1177811

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.

我想通过 Ajax 将完全动态的 php 页面加载到选项卡中。例如,我想在链接中包含 $_GET 值,基于它是哪个选项卡 - 如果您的选项卡是动态的,例如基于数据库数据,这很有用。找不到任何可以使用它的东西,但我确实设法编写了一些实际工作的 jQuery,并且可以满足我的要求。我是一个完整的 jQuery 菜鸟,但我是这样做的。

  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.
  1. 我创建了一个名为 tabajax(而不仅仅是 tab)的新“数据切换”选项,这使我能够区分 ajax 和静态内容。
  2. 我创建了一个基于该数据切换运行的 jQuery 片段,它不会与原始代码混淆。

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

我现在可以将 url.php?value=x 加载到我的 Bootstrap 标签中。

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

如果你愿意,请随意使用它,代码如下

jQuery code:

jQuery代码:

$('[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:

HTML:

<li><a href="tabs/loadme.php?value=1" data-target='#val1' data-toggle="tabajax">Val 1</a></li>

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).

所以在这里你可以看到我改变了引导程序加载的方式,我使用了动态ajaxlink的href,然后向链接添加了一个'data-target'值,这应该是你的目标div(tab-content) .

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

因此,在您的选项卡内容部分,您应该为此示例创建一个名为 val1 的空 div。

Empty Div (target):

空 Div(目标):

<div class='tab-pane' id='val1'><!-- Ajax content will be loaded here--></div>

Hope this is useful to someone :)

希望这对某人有用:)

回答by Pierre de LESPINAY

I suggest to put the uriinto the tab-paneelements, it allows to take advantage of web frameworks reverse urlfonctionnalities. It also allows to depend exclusively on the markup

我建议将uri放入tab-pane元素中,它允许利用 web 框架反向 url功能。它还允许完全依赖于标记

<ul class="nav nav-tabs" id="ajax_tabs">
  <li class="active"><a data-toggle="tab" href="#ajax_login">Login</a></li>
  <li><a data-toggle="tab" href="#ajax_registration">Registration</a></li>
</ul>
<div class="tab-content">
  <div class="tab-pane active" id="ajax_login"
    data-target="{% url common.views.ajax_login %}"></div>
  <div class="tab-pane" id="ajax_registration"
    data-target="{% url common.views.ajax_registration %}"></div>
</div>

And here is the javascript

这是 javascript

function show_tab(tab) {
    if (!tab.html()) {
        tab.load(tab.attr('data-target'));
    }
}

function init_tabs() {
    show_tab($('.tab-pane.active'));
    $('a[data-toggle="tab"]').on('show', function(e) {
        tab = $('#' + $(e.target).attr('href').substr(1));
        show_tab(tab);
    });
}

$(function () {
    init_tabs();
});

I loads the active tab, and loads a tab only if it is not already loaded

我加载活动选项卡,并仅在尚未加载时加载选项卡

回答by jmartsch

There is an error in your code user1177811.

您的代码 user1177811 中存在错误。

It has to be $('[data-toggle="tabajax"]').

它必须是$('[data-toggle="tabajax"]')

Also there is room for improvement. The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. So i added #contentto load the content div of the remote page.

也有改进的余地。.load() 方法与 $.get() 不同,它允许我们指定要插入的远程文档的一部分。所以我添加#content了加载远程页面的内容div。

$this.tab('show');is now only called, when response was a success.

$this.tab('show');现在只在响应成功时调用。

Here is the code

这是代码

 $('[data-toggle="tabajax"]').click(function(e) {
        e.preventDefault();
        $this = $(this);
        var loadurl = $(this).attr('href');
        var targ = $(this).attr('data-target');
        $(targ).load(loadurl+'?ajax=true #content', function(){
            $this.tab('show');
        });
    });

回答by Matt Rardon

Here is how I do it. I utilize an attribute data-hrefwhich 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.

这是我如何做到的。我利用一个属性data-href来保存我想在节目中加载的 url。这不会重新加载已经加载的数据,除非您设置$('#tab').data('loaded');为 0 或将其删除。它还通过检测第一个斜杠的位置来处理相对与绝对 url。我不确定与所有浏览器的兼容性,但它适用于我们的情况并允许我们正在寻找的功能。

Javascript:

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:

HTML:

<div class="tabbable">
  <ul class="nav nav-tabs">
    <li class="active">
      <a href="#js-tab1" data-href="tab1.php" data-toggle="tab">Tab 1</a>
    </li>
  </ul>
  <div class="tab-content">
    <div class="tab-pane active" id="js-tab1">
      <p>
        This content isn't used, but instead replaced with contents of tab1.php.
      </p>
      <p>
        You can put a loader image in here if you want
      </p>
    </div>
  </div>
</div>

回答by howler

Here is a solution I have found - and modified to suit my needs:

这是我找到的解决方案 - 并根据我的需要进行了修改:

$("#tabletabs").tab(); // initialize tabs
$("#tabletabs").bind("show", function(e) { 
var contentID = $(e.target).attr("data-target");
var contentURL = $(e.target).attr("href");
if (typeof(contentURL) != 'undefined') { // Check if URL exists
$(contentID).load(contentURL, function(){
$("#tabletabs").tab(); // reinitialize tabs
});
} else {
$(contentID).tab('show');
}
});
$('#tabletabs a:first').tab("show"); // Load and display content for first tab
});

回答by Chad Kuehn

This is an MVC example using Razor. It will interact with two partial views named: _SearchTab.cshtmland _SubmissionTab.cshtml

这是一个使用 Razor 的 MVC 示例。它将与两个名为的局部视图交互:_SearchTab.cshtml_SubmissionTab.cshtml

Notice that I am naming the id of the tabs the same as the partials.

请注意,我将选项卡的 id 命名为与部分相同的名称。

Markup:

标记:

<!-- Nav tabs -->
<ul id="tabstrip" class="nav nav-tabs" role="tablist">
    <li class="active"><a href="#_SubmissionTab" role="tab" data-toggle="tab">Submission</a></li>
    <li><a href="#_SearchTab" role="tab" data-toggle="tab">Search</a></li>
</ul>

<!-- Tab panes -->
<div class="tab-content">
    <div class="tab-pane fade in active" id="_SubmissionTab">@Html.Partial("_SubmissionTab")</div>
    <div class="tab-pane fade" id="_SearchTab"></div>
</div>

The @Html.Partialwill request the page on the active tab on page load

@Html.Partial会要求在页面加载活动选项卡页面

Script:

脚本:

<script>
    $('#tabstrip a').click(function (e) {
        e.preventDefault()
        var tabID = $(this).attr("href").substr(1);
        $("#" + tabID).load("/@ViewContext.RouteData.Values["controller"]/" + tabID)
        $(this).tab('show')
    })
</script>

The loadfunction will perform an ajax request as each tab is clicked. As for what path is requested you will notice a @ViewContext.RouteData.Values["controller"]call. It simply gets the controller of the current view assuming the partial views are located there.

load函数将在单击每个选项卡时执行 ajax 请求。至于请求什么路径,你会注意到一个@ViewContext.RouteData.Values["controller"]调用。假设局部视图位于那里,它只是获取当前视图的控制器。

Controller:

控制器:

    public ActionResult _SubmissionTab()
    {
        return PartialView();
    }

    public ActionResult _SearchTab()
    {
        return PartialView();
    }

The controller is needed to relay the loadrequest to the proper partial view.

需要控制器将load请求中继到适当的局部视图。

回答by Nikunj K.

Here is the Bootstrap tab Ajax example, you can use it...

这是 Bootstrap 选项卡 Ajax 示例,您可以使用它...

<ul class="nav nav-tabs tabs-up" id="friends">
      <li><a href="/gh/gist/response.html/3843293/" data-target="#contacts" class="media_node active span" id="contacts_tab" data-toggle="tabajax" rel="tooltip"> Contacts </a></li>
      <li><a href="/gh/gist/response.html/3843301/" data-target="#friends_list" class="media_node span" id="friends_list_tab" data-toggle="tabajax" rel="tooltip"> Friends list</a></li>
      <li><a href="/gh/gist/response.html/3843306/" data-target="#awaiting_request" class="media_node span" id="awaiting_request_tab" data-toggle="tabajax" rel="tooltip">Awaiting request</a></li>
</ul>

<div class="tab-content">
<div class="tab-pane active" id="contacts">
</div>
      <div class="tab-pane" id="friends_list">

      </div>
      <div class="tab-pane  urlbox span8" id="awaiting_request">

      </div>
    </div>

and here is the AJAX call

这是 AJAX 调用

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

    $.get(loadurl, function(data) {
        $(targ).html(data);
    });

    $this.tab('show');
    return false;
});

回答by Marcelo Agimóvel

I use this function and it's really nice because she prevent's you from load ajax again when going back to that tab.

我使用这个功能,它真的很好,因为当你回到那个选项卡时,她阻止了你再次加载 ajax。

Tip: on tab href, just put the destination. Add this to footer:

提示:在 tab href 上,只需输入目的地即可。将此添加到页脚:

$("#templates_tabs").tabs({
    beforeLoad: function( event, ui ) {
      if (ui.tab.data("loaded")) {
          event.preventDefault();

          return;
      }


      ui.ajaxSettings.cache = false,
      ui.jqXHR.success(function() {

          ui.tab.data( "loaded", true );
      }),
      ui.jqXHR.error(function () {


          ui.panel.html(
          "Not possible to load. Are you connected?");
      });
    }
  });