将bootstrap工具提示设置为AJAX调用结果

woo*_*gie 6 javascript ajax jquery twitter-bootstrap

我有一个bootstrap工具提示,我想从AJAX请求加载数据,请求中的文本title是工具提示的属性.我的AJAX请求工作正常,但我有两个问题:

  1. 为什么来自AJAX调用的数据不会进入工具提示?
  2. 如何使用我的ttManager对象封装工具提示的状态?

目前,当页面首次加载并且我#btnSubmit在控制台中单击时,我看到 success来自console.log(ttManager)行的正确数据

 $(document).ready(function () {
        //this object's title attribute will be the value of ttManager.title seen below
        var ttManager = {
            title: '',
            setTitle: function (data) {
                this.title = data;
            }
        }
        var ajaxCall = function () {
            //this returns the top five results of text from a query
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "Service.asmx/GetDrugs",
                dataType: "json",
                success: function (data) {
                    console.log('success');
                    ttManager.title = data.d;
                    //inside this function I want to set ttManager.title equal to the data.d
                    console.log(ttManager);




                },
                error: function (xhr) {
                    console.log('failed: ' + xhr.status);
                }

            });


        }

        $('#btnSubmit').tooltip({
            //reference to ajax call
            //title is the attribute responsible for displaying text in the tooltip
            //I need to use a reusable object to set the text property instead of referencing ajaxCall
            //would it be better if there below were title: ttManager.title?
            title: ajaxCall,
            trigger: 'click',
            placement: 'right'
        });



    });
Run Code Online (Sandbox Code Playgroud)

我很确定我需要一个回调函数,但我不知道在哪里.任何未来的指针也将受到赞赏.谢谢.

Snu*_*gus 8

首先,对bootstrap的工具提示插件进行一点解释.显示的工具提示将从elements title属性中拉出(如果存在),否则将使用传递的title参数.

接下来你需要了解的是ajax调用是异步的.这意味着代码将在等待响应时继续运行.所以,例如,如果我做这样的事情

$.ajax({
    URL: 'google.com',
    success: function(){
        console.log('yay');
    }
});
console.log('woohoo');
Run Code Online (Sandbox Code Playgroud)

你会在"yay"之前在控制台中看到"woohoo".所以,目前,$('#btnSubmit').tooltip在ajax查询改变了ttManager的状态之前,你正在调用.

另一个问题是你目前没有对ttManager做任何关于bootstrap的事情.我觉得我还应该提到ttManager对象在这里似乎毫无意义.

就个人而言,我会将我的ajax成功函数更改为此(设置title属性,调用工具提示,然后生成另一个单击以显示工具提示)

success: function(data) {
    $('#btnSubmit').attr('title', data.d)
    .tooltip({
        trigger: 'click',
        placement: 'right'
    }).click();
}
Run Code Online (Sandbox Code Playgroud)

删除$('#btnSubmit').tooltip...当前存在的当前代码,并添加一次性单击处理程序以调用您的ajax.

$('#btnSubmit').one('click', function() {
    ajaxCall();
});
Run Code Online (Sandbox Code Playgroud)