jQuery UI自动完成选择从json获取所有值

时间:2017-10-17 06:45:16

标签: javascript jquery jquery-ui-autocomplete

JSON有键:id,n和d。我需要获取所选项目的ID' id'和' n'为了创建一个网址。

  $.ajax({
    type: "GET",
    url: "q.json",
    success: function(data) {
      var items = [];
      $.each(data, function(key, val) {
        items.push(val);
      });

      $("#tags").autocomplete({ 
        maxResults: 4,
        minLength: 2,
        source: function(request, response) {
          var filteredArray = $.map(items, function(item) {
            if (item.n.toUpperCase().indexOf(request.term.toUpperCase()) == 0) {
              return item.n + " ("+item.d+")";
            } else {
              return null;
            }
          });
          response(filteredArray.slice(0, this.options.maxResults));
        },
        select: function(event, ui) {
          alert("you selected " + ui.item.id);
          window.location.href = ui.item.id+"-"+ui.item.n;
        }
      });

    }
  });

如何达到预期效果?

1 个答案:

答案 0 :(得分:0)

我在JSON中有3个键,必须在select:function(event,ui)

中获取它们
      $("#tags").autocomplete({ 
          maxResults: 4,
          minLength: 2,
          source: function(request, response) {
            var filteredArray = $.map(items, function(item) {
              if (item.n.toUpperCase().indexOf(request.term.toUpperCase()) == 0) {
                return {
                  id: item.id
                  label: item.n + " ("+item.d+")",
                }
              } else {
                return null;
              }
            });
            response(filteredArray.slice(0, this.options.maxResults));
          },
          select: function(event, ui) {
            event.preventDefault();
            $("#tags").val(ui.item.label);
            window.location.href = ui.item.id+"-"+ui.item.n;
          },
        });

      });