jQuery自动完成minLength和maxResults无法正常工作

时间:2018-02-08 09:00:47

标签: jquery json

我在我的项目中使用jQuery自动完成功能,似乎无法让minLength正常工作。它将在1个按键上触发,我只想在4之后显示结果。我的json文件有超过300个可以返回的值,所以我也想使用maxResults这似乎也没有为我工作

谁能告诉我我做错了什么?

Fiddle

JSON

{
"projectList": [{
        "label": "Some project",
        "id": "BP003",
        "desc": "Description 1"
    },
    {
        "label": "Some other project",
        "id": "BP065",
        "desc": "Description 2"
    },
    {
        "label": "Complementary ICR",
        "id": "BP122",
        "desc": "Description 3"
    },
    {
        "label": "Project 1",
        "id": "BP129",
        "desc": "Description 4"
    },
    {
        "label": "Another one",
        "id": "BP132",
        "desc": "Description 5"
    }
]

}



$("#project").autocomplete({
      source: function (request, response) {
        var regex = new RegExp(request.term, 'i');
        $.ajax({
          url: "projects.json",
          dataType: "json",
          minLength: 4,
          maxResults: 10,
          success: function (data) {
            response($.map(data.projectList, function (item) {
              if (regex.test(item.id)) {
                return {
                  label: item.label,
                  id: item.id
                };
              }
              if (regex.test(item.label)) {
                return {
                  label: item.label,
                  id: item.id
                };
              }
            }));
            
          }
        });
        
      }
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="form-control full-width" id="project" type="text" />
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

minLength maxResults 是自动填充的属性,而不是ajax。

$("#project").autocomplete({
      minLength: 4,
      source: function (request, response) {
        var regex = new RegExp(request.term, 'i');
        $.ajax({
          url: testURL,
          dataType: "json",

          maxResults: 10,
          success: function (data) {
            response($.map(data.projectList, function (item) {
              if (regex.test(item.id)) {
                return {
                  label: item.label,
                  id: item.id
                };
              }
              if (regex.test(item.label)) {
                return {
                  label: item.label,
                  id: item.id
                };
              }
            }));

          }
        });

      }
    });