在javascript中更新bootstrap typeahead中的数据源

时间:2012-03-27 21:38:12

标签: javascript ajax twitter-bootstrap

我希望下拉选项能够反映存储在名为companyinfo.js的文件中的所有项目,我通过ajax请求。我在页面加载时调用dropDownList()

function dropDownList (evt) {
    console.log("dropdownfired");
    var companyArray = [];
    $.ajax({
        url : 'assets/data/companyarray.js', //this file is just ["Facbeook", "Twitter", "Klout",]
        dataType: 'script',
        success: function(data) {
            companyArray = data;
            console.log(companyArray); //returns an array of the companies
            $('#companyInput1').attr('data-source', companyArray); //#companyInput1 is the input field where I want the typehead to be
            console.log($('#companyInput1').attr('data-source')); //returns undefined
        }
    });
}

更新

function dropDownList (evt) {
    console.log("dropdownfired");
    var companyArray = [];
    $.ajax({
        url : 'assets/data/companyarray.js', //this file is just ["Facbeook", "Twitter", "Klout",]
        dataType: 'script',
        success: function(data) {
            companyArray = data;
           console.log(companyArray); // gives array of companies
            $('#companyInput1').data('data-source', companyArray);
            console.log($('#companyInput1').data('data-source')); // gives undefined still
        }
    });
}​

1 个答案:

答案 0 :(得分:0)

除了字符串之外,不应将任何内容存储为HTML节点上的属性。要存储数组,请使用.data()-method jquery提供

success: function(data) {
        companyArray = data;
        console.log(companyArray); //returns an array of the companies
        $('#companyInput1').data('data-source', companyArray); //#companyInput1 is the input field where I want the typehead to be
        console.log($('#companyInput1').data('data-source')); //should work
    }