【问题标题】:jquery autocomplete with an ajax call to generate the array带有ajax调用的jquery自动完成以生成数组
【发布时间】:2014-11-08 01:19:14
【问题描述】:

我正在尝试对我通过 ajax 调用从 db 获得的一些国家/地区进行 jquery ui 自动完成

我正在为如何将值表传递给自动完成而苦恼

 $( document ).ready(function() {

    $.ajax({
        url:Routing.generate('e_veilleur_user_register_countries_autocomplete'),
        type:"get",
        dataType: 'json',
        data: 'test=cool',
        async: true,
        cache: true,
        success: function(data){
            var availableTags = data;
        }
    });

    $( "#fos_user_registration_form_pays" ).autocomplete({
        source: availableTags
    });
  });

我的ajax调用的结果是

[{"countryName":"United States"},
 {"countryName":"Canada"},
 {"countryName":"Afghanistan"},
 {"countryName":"Albania"},
 {"countryName":"Algeria"}

给出的错误:availableTags is not defined

【问题讨论】:

  • AJAX 是异步的,您在 AJAX 完成之前使用 availableTags。 jQuery Autocomplete 允许您在 source: 选项中指定 AJAX URL,使用它。
  • 确实!但是每次我输入一个 url 都会调用 ajax,对吗?我想在开始时加载整个数组,可以吗?或者我错了,把 url 预加载数组

标签: jquery ajax autocomplete


【解决方案1】:

您可以对源代码使用自定义函数,而该函数使用 AJAX。因此,您不必与范围外的 AJAX 调用同步。

$( "#fos_user_registration_form_pays" ).autocomplete({
    source: function(request, response) {
       $.ajax({
       url:Routing.generate('e_veilleur_user_register_countries_autocomplete'),
       type:"get",
       dataType: 'json',
       data: 'test=cool',
       async: true,
       cache: true,
       success: function(data){
          response(data);
       }
     });
    }
});

jQuery UI Autocomplete Source

编辑

到目前为止,我还没有看到评论。回答该特定评论后,您可以从 AJAX 中调用自动完成功能。

$.ajax({
    url:Routing.generate('e_veilleur_user_register_countries_autocomplete'),
    type:"get",
    dataType: 'json',
    data: 'test=cool',
    async: true,
    cache: true,
    success: function(data){
        $( "#fos_user_registration_form_pays" ).autocomplete({
        source: data
        });
    }
});

【讨论】:

    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 2013-11-08
    相关资源
    最近更新 更多