jQuery自动完成不会循环遍历XML数据

时间:2016-03-30 09:03:46

标签: javascript jquery xml jquery-ui autocomplete

目前,我似乎无法从我的XML文件中检索任何数据。以下是代码;

$(document).ready(function() {
    setTimeout(function() {
        $('#_Q0').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "brands.xml",
                    dataType: "xml",
                    type: "GET",
                    success: function(xml) {
                        var results = [];
                        $(xml).find("brand").each(function() {
                            if (results.indexOf(request.term.toUpperCase()) >= 0) {
                                results.push(results);
                            }
                        });
                        response(results);
                    }
                });
            },
            autoFocus: true,
            minLength: 3,
            response: function(event, ui) {
                if (!ui.content.length) {
                    var noResult = {
                        value: "",
                        label: "No results found"
                    };
                    ui.content.push(noResult);
                }
            }
        });
        var render = $('#_Q0').autocomplete('instance')._renderMenu;
        $('#_Q0').autocomplete('instance')._renderMenu = function(ul, items) {
            items.push({
                label: 'AUTRE MARQUE',
                value: 'AUTRE MARQUE',
                last: true
            });
            render.call(this, ul, items);
        };
    }, 100);
});

这是一个Plunk;

https://plnkr.co/edit/QFOYcJc7iQ8UQc0e5SKH?p=preview

我以前使用的是JSON源代码,但现在必须切换到XML。

提前致谢

1 个答案:

答案 0 :(得分:0)

问题在于处理xml

$(document).ready(function() {
  setTimeout(function() {
    $('#_Q0').autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "brands.xml",
          dataType: "xml",
          type: "GET",
          success: function(xml) {
            var term = request.term.toLowerCase();
            var results = $(xml).find("brand").filter(function() {
              return $(this).attr('label').toLowerCase().indexOf(term) > -1;
            }).map(function() {
              return {
                label: $(this).attr('label')
              }
            }).get();
            response(results, xml);
          }
        });
      },
      autoFocus: true,
      minLength: 3,
      response: function(event, ui) {
        if (!ui.content.length) {
          var noResult = {
            value: "",
            label: "No results found"
          };
          ui.content.push(noResult);
        }
      }
    });
    var render = $('#_Q0').autocomplete('instance')._renderMenu;
    $('#_Q0').autocomplete('instance')._renderMenu = function(ul, items) {
      items.push({
        label: 'AUTRE MARQUE',
        value: 'AUTRE MARQUE',
        last: true
      });
      render.call(this, ul, items);
    };
  }, 100);
});

演示:Plunker