jQuery使用对象自动完成更新源 - 格式化数组

时间:2012-10-30 16:57:34

标签: javascript jquery user-interface autocomplete jquery-autocomplete

我试图动态更新jQuery UI源代码。我可以使用如下数组做到这一点:

  var arrProducts = ['cheese' , 'bread' ,  'milk'];

但需要使用对象来做。在切换到使用AJAX之前,这在第一页加载时工作正常,将一组对象从PHP传入Twig:

 var arrProducts = [
                      {% for product in allproducts %}
                          {
                              title:  "{{ product.title }}",
                              url:  "{{ product.url }}",                                 
                              label: "{{ product.label }}"                              
                          },
                      {% endfor %}
              ];

那么,我怎样才能在javascript中复制这种格式?我试过这个:

                           var arrProducts = [];

                            $.each(data.products, function(index, product)
                            {
                                   prod['title'] = product.title;
                                   prod['url'] = product.url;
                                   prod['label'] = product.label;

                                   arrProducts.push(prod);
                            });                          

                           $('.searchBox' ).autocomplete( "option", "source", arrProducts );

但是这产生了嵌套对象,然后自动完成似乎无法正确读取。

1 个答案:

答案 0 :(得分:1)

jQueryUI文档表明source数组应包含具有labelvalue属性的对象:http://api.jqueryui.com/autocomplete/#option-source;您的对象上没有value属性。

我不清楚为什么以前会有效,但这里有一个对我有用的修改:我将prod['title']更改为prod['value'],并预先声明prod作为局部变量它不会被自动实例化为全局。

另请注意,我必须更改“选项”调用才能使用匿名对象;出于某种原因,尝试调用$('.searchBox').autocomplete("options", "source", arrProducts);会导致我的测试小提琴出错。

<强> HTML

​<input type="text" class="searchBox"/>​​​​​​​​​​​​​​​​​​​​​​​​​​​

<强>的JavaScript

var products = [
    {
      title: 'cheese',
      url: 'http://www.example.com',
      label: 'Swiss Cheese'
    },
    {
      title: 'bread',
      url: 'http://www.example.com',
      label: 'Wheat Bread'
    },
    {
      title: 'milk',
      url: 'http://www.example.com',
      label: '1% Milk'},
];

var arrProducts = [];

$.each(products, function(index, product) {
    var prod = {};
    prod['value'] = product.title;
    prod['url'] = product.url;
    prod['label'] = product.label;

    arrProducts.push(prod);
});

$('.searchBox').autocomplete({ source: arrProducts });