在Bootstrap预先输入函数中使用时,为什么AJAX/JSON响应未定义?

tre*_*lez 2 javascript jquery json twitter-bootstrap

我创建了一个函数,它生成一个返回JSON字符串的jquery AJAX调用.它本身工作正常 - 当我将字符串输出到控制台(console.log)时,我可以看到JSON字符串输出.

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

但是,当我设置一个变量来包含该函数调用的输出时:

var mydata = getJSONCustomers();

,然后尝试在我的Twitter-Bootstrap TypeAhead函数中使用它(表单的自动完成):

data = mydata;
console.log(data);
Run Code Online (Sandbox Code Playgroud)

我的控制台出现"未定义"错误.

以下是此代码的片段:

$(document).ready(function() {

var mydata = getJSONCustomers();

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

        data = mydata;
        console.log(data);

 // multiple .typeahead functions follow......
});
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我将数据变量设置为从AJAX函数返回的硬编码JSON字符串,一切正常:

data = [{"CustNameShort": "CUS1", "CustNameLong": "Customer One"}]
Run Code Online (Sandbox Code Playgroud)

如何在我的预先输入函数中使用JSON字符串?

Fel*_*ing 5

.responseText返回一个字符串.您必须首先解析字符串才能使用数组:

var mydata = JSON.parse(getJSONCustomers());
Run Code Online (Sandbox Code Playgroud)

话虽这么说,你应该避免进行同步调用.看看如何从异步调用返回响应?了解如何使用回调/承诺.