jQuery 为什么在 Bootstrap 预先输入功能中使用 AJAX/JSON 响应时未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17532967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:15:32  来源:igfitidea点击:

Why is AJAX/JSON response undefined when used in Bootstrap typeahead function?

javascriptjsonjquerytwitter-bootstrap

提问by tresstylez

I created a function that makes a jquery AJAX call that returns a JSON string. On its own, it works fine -- and I can see the JSON string output when I output the string to the console (console.log).

我创建了一个函数,它进行 jquery AJAX 调用,返回一个 JSON 字符串。就其本身而言,它工作正常——当我将字符串输出到控制台 ( console.log)时,我可以看到 JSON 字符串输出。

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

However, when I set a variable to contain the output of that function call:

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

var mydata = getJSONCustomers();

var mydata = getJSONCustomers();

, then try to use it within my Twitter-Bootstrap TypeAheadfunction (autocomplete for forms):

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

data = mydata;
console.log(data);

I get an 'undefined' error in my console.

我的控制台出现“未定义”错误。

Below is a snippet of this code:

下面是这段代码的一个片段:

$(document).ready(function() {

var mydata = getJSONCustomers();

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

        data = mydata;
        console.log(data);

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

Interesting here, is that if I set the data variable to be the hardcoded JSON string returned from the AJAX function, everything works fine:

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

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

How can I use the JSON string within my typeahead function?

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

回答by Felix Kling

.responseTextreturns a string. You have to parse the string first to be able to work with the array:

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

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

That being said, you should avoid making synchronous calls. Have a look at How do I return the response from an asynchronous call?to get an idea about how to work with callbacks/promises.

话虽如此,您应该避免进行同步调用。看看如何从异步调用返回响应?了解如何使用回调/承诺。

回答by Dzulqarnain Nasir

The problem is that the Ajax request hasn't had the chance to complete before typeahead is initialised, so typeahead is initialised with an uninitialised mydata variable. Also, as of jQuery 1.8+ async: falsehas been deprecated and you need to use the complete/success/error callbacks.

问题是 Ajax 请求在 typeahead 初始化之前没有机会完成,所以 typeahead 是用未初始化的 mydata 变量初始化的。此外,从 jQuery 1.8+async: false开始,已弃用,您需要使用 complete/success/error 回调。

Try this:

尝试这个:

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

And then you could do something like:

然后你可以做这样的事情:

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......
    });
});

So your code completes the Ajax call before initialising the typeahead plugin.

所以你的代码在初始化 typeahead 插件之前完成了 Ajax 调用。