2017-08-23 69 views
-1

我正在使用typeahead JS在我的控件中設置typeaheads。Ajax Jquery對象不能像JavaScript對象那樣工作

代碼輸入類對象的數組是這樣的:

 var companylist2 = [ 
      { word: "Alabama" }, 
      { word: "Alaska" }, 
      { word: "Arizona" }, 
      { word: "Arkansas" }, 
      { word: "California" }, 
      { word: "Colorado" } 
     ]; 


     // Get Company Name Typeahead 
     var states = new Bloodhound({ 
      datumTokenizer: function (d) { 
       return Bloodhound.tokenizers.whitespace(d.word); 
      }, 
      queryTokenizer: Bloodhound.tokenizers.whitespace, 
      limit: 5, 
      local: companylist2 
     }); 

不過,我想,所以我用Ajax的jQuery來填充這樣的類對象的數組從我的後端動態設置:

 $(function() { 
      $.ajax({ 
       type: "POST", 
       url: "mypage.aspx/getCompanylist", 
       contentType: "application/json", 
       dataType: "json", 
       success: function (msg) { 
        companylist = msg.d; 
        alert(companylist[0]["word"]); 
        alert(companylist[1]["word"]); 
       } 
      }); 
     }); 

爲companylist [0] [「字」]和companylist [1] [「字」]都顯示我希望它顯示什麼,但警報當我改變源到一個從我的JQuery的打字頭不起作用

+0

BloodHound允許遠程源...請參閱[它們的文檔](https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#remote) –

回答

0

儘量配置在事先鍵入的內容success

$(function() { 
    $.ajax({ 
     type: "POST", 
     url: "mypage.aspx/getCompanylist", 
     contentType: "application/json", 
     dataType: "json", 
     success: function (msg) { 
      companylist = msg.d; 
      alert(companylist[0]["word"]); 
      alert(companylist[1]["word"]); 

      // Get Company Name Typeahead 
      var states = new Bloodhound({ 
       datumTokenizer: function (d) { 
        return Bloodhound.tokenizers.whitespace(d.word); 
       }, 
       queryTokenizer: Bloodhound.tokenizers.whitespace, 
       limit: 5, 
       local: companylist 
      }); 

     } 
    }); 
}); 

也許CallbackAsynchronous幫助。

+0

將其移入並運行。 。不知道爲什麼,但是我的公司列表是在$(函數 –

+0

'$ .ajax''' success'函數是一個異步回調函數)之外發起的。參見[回調](https://developer.mozilla.org/en-US/ docs/Glossary/Callback_function)和[Asynchronous](https://developer.mozilla.org/en-US/docs/Glossary/asynchronous)。 – leaf

相關問題