简体   繁体   English

自动完成功能不起作用

[英]Autocomplete doesn't work

I have an issue with the auto complete in js. 我在js中自动完成有问题。 Here the following code works well for me: 下面的代码对我来说很有效:

$(function(){
    $( "#txtAuto" ).autocomplete({
        source: ["Choice1","Choice2"],
        minLength:2     
    });
});

But when I change this to the code below for testing it doesn't gives me choices: 但是,当我将其更改为下面的代码进行测试时,它没有给我选择:

$(function(){
    $( "#txtAuto" ).autocomplete({
        source: function( request, response ){
            $.ajax({
                url: "test.ewd",
                success: function(data){
                    var res=data.match('\\[[^\\]]*]');
                    return ["Choice1", "Choice2"];                       
                }
            });
        },
        minLength:2     
    });
});

Any one tell me where I did mistake? 有人告诉我我在哪里做错了吗?

The core of the problem is that the ajax-function is asynchronous. 问题的核心是ajax函数是异步的。 It is not executed at the same time as the rest of your code, but rather when the response for your ajax-request (which probably takes 10-100 ms to complete) is available. 它不会与其余代码同时执行,而是在对ajax请求的响应(可能需要10到100毫秒才能完成)可用时执行。

So, you can't return the values from the success -function. 因此,您无法从success函数return值。 Instead, you must pass them in to the response function. 相反,您必须将它们传递给response函数。 like this: 像这样:

success: function(data) {
  var res=data.match('\\[[^\\]]*]');
  response(["Choice1", "Choice2"]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM