7

我有一个引导工具提示,我想从 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'
        });



    });

我很确定我在某个地方需要一个回调函数,但我不确定在哪里。任何未来的指针也将不胜感激。谢谢。

4

1 回答 1

9

首先对bootstrap的tooltip插件做一点说明。title如果存在,则显示的工具提示将从元素属性中提取,否则它将使用传递的标题参数。

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

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

您会在“yay”之前在控制台中看到“woohoo”。因此,目前,您在$('#btnSubmit').tooltipajax 查询更改 ttManager 的状态之前调用。

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

就个人而言,我会将我的 ajax 成功函数更改为此(设置标题属性,调用工具提示,然后再次单击以使工具提示出现)

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

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

$('#btnSubmit').one('click', function() {
    ajaxCall();
});
于 2013-10-14T21:36:59.550 回答