2013-07-08 36 views
2

我創建了一個函數,它使jQuery AJAX調用返回一個JSON字符串。就其本身而言,它工作正常 - 當我將字符串輸出到控制檯(console.log)時,我可以看到JSON字符串輸出。爲什麼在Bootstrap typeahead函數中使用AJAX/JSON響應時未定義?

function getJSONCustomers() 
{ 
var response = $.ajax({ 
    type: "GET", 
    url: "getCustomers.php", 
    dataType: "json", 
    async: false, 
    cache: false 
    }).responseText; 
    return response; 
}; 

但是,當我設置一個變量包含函數調用的輸出:

var mydata = getJSONCustomers();

,然後嘗試我Twitter的引導預輸入功能(自動完成對內使用形式):

data = mydata; 
console.log(data); 

我得到了我的控制檯 '未定義' 的錯誤。

以下是該代碼的一個片段:

$(document).ready(function() { 

var mydata = getJSONCustomers(); 

$('#Customer').typeahead({ 
    source: function (query, process) { 
     customers = []; 
     map = {}; 

     data = mydata; 
     console.log(data); 

// multiple .typeahead functions follow...... 
}); 

這裏比較有意思的是,如果我設置的數據變量是從AJAX函數返回的硬編碼的JSON字符串,一切工作正常:

data = [{"CustNameShort": "CUS1", "CustNameLong": "Customer One"}] 

如何在我的typeahead函數中使用JSON字符串?

+0

我認爲這與同步代碼有關,但我不確定。原始(工作)'console.log'去了哪裏? –

+0

我可以調用var mydata = getJSONCustomers(); - 然後立即做一個console.log(mydata),它工作正常。只有在我處於鍵入區塊之後,它纔會停止工作。 – tresstylez

+0

「如果我將數據變量設置爲硬編碼的JSON字符串」 - 您不知道。您爲其分配一個包含一個對象的數組。 – zeroflagL

回答

5

.responseText返回a 字符串。你必須先分析字符串能夠與該陣列的工作:

var mydata = JSON.parse(getJSONCustomers()); 

話雖這麼說,你應該避免同步調用。查看How do I return the response from an asynchronous call?瞭解如何使用回調/承諾。

-1

問題是在初始化typeahead之前Ajax請求還沒有完成,所以typeahead被初始化爲未初始化的mydata變量。此外,截至jQuery 1.8 + async: false已被棄用,你需要使用完整/成功/錯誤回調。

試試這個:

function getJSONCustomers(callback) { 
    $.ajax({ 
     type: "GET", 
     url: "getCustomers.php", 
     dataType: "json", 
     cache: false, 
     success: callback 
    }); 
}; 

然後,你可以這樣做:

getJSONCustomers(function(mydata) { 
    // mydata contains data retrieved by the getJSONCustomers code 
    $('#Customer').typeahead({ 
     source: function (query, process) { 
      customers = []; 
      map = {}; 
      console.log(mydata); 

// multiple .typeahead functions follow...... 
    }); 
}); 

所以,你的代碼完成初始化的預輸入插件之前Ajax調用。

+2

OP發出同步請求,所以這不是問題。 –

+0

啊你說得對。傻我。 –

相關問題