如何在JQuery UI自动完成中使用source:function()…和AJAX


78

我需要有关JQuery UI自动完成功能的帮助。我希望我的文本字段(.suggest-user)显示来自AJAX请求的名称。这就是我所拥有的:

jQuery("input.suggest-user").autocomplete({
    source : function(request, response) {
        var name = jQuery("input.suggest-user").val();
        jQuery.get("usernames.action?query=" + name, function(data) {
            console.log(data);  // Ok, I get the data. Data looks like that:
            test = data;        // ["one@abc.de", "onf@abc.de","ong@abc.de"]
            return test;        // But what now? How do I display my data?
        });
    },
    minLength : 3
});

很感谢任何形式的帮助。

Answers:


153

在您的AJAX回调内部,您需要调用该response函数;传递包含要显示项目的数组。

jQuery("input.suggest-user").autocomplete({
    source: function (request, response) {
        jQuery.get("usernames.action", {
            query: request.term
        }, function (data) {
            // assuming data is a JavaScript array such as
            // ["one@abc.de", "onf@abc.de","ong@abc.de"]
            // and not a string
            response(data);
        });
    },
    minLength: 3
});

如果响应JSON与jQuery UI自动完成接受的格式不匹配,则必须在将结果传递给响应回调之前在AJAX回调内部转换结果。请参阅此问题和可接受的答案


2
这有点简单。jQuery自动完成功能支持“源”参数的获取网址。source: "usernames.action" 。您的方法应返回一个json数组,并应接受一个称为“ term”的参数。
伊丽莎白2014年

@Elisa:对。OP在示例中使用了回调(可能是有原因的),因此我也照做。
Salman A

这对我不起作用...它将返回列表中的所有项目,而不是与查询词匹配的项目。
geoidesic 2015年

OP在服务器端过滤结果,该答案假设是这样。
Salman A

1
@LoryLory如果要修改自动完成的建议列表,则在stackoverflow中搜索“ jquery ui自动完成_renderItem”。
Salman A

33

试试这个代码。您可以使用$.get代替$.ajax

$( "input.suggest-user" ).autocomplete({
    source: function( request, response ) {
        $.ajax({
            dataType: "json",
            type : 'Get',
            url: 'yourURL',
            success: function(data) {
                $('input.suggest-user').removeClass('ui-autocomplete-loading');  
                // hide loading image

                response( $.map( data, function(item) {
                    // your operation on data
                }));
            },
            error: function(data) {
                $('input.suggest-user').removeClass('ui-autocomplete-loading');  
            }
        });
    },
    minLength: 3,
    open: function() {},
    close: function() {},
    focus: function(event,ui) {},
    select: function(event, ui) {}
});

18
$("#id").autocomplete(
{
    search: function () {},
    source: function (request, response)
    {
        $.ajax(
        {
            url: ,
            dataType: "json",
            data:
            {
                term: request.term,
            },
            success: function (data)
            {
                response(data);
            }
        });
    },
    minLength: 2,
    select: function (event, ui)
    {
        var test = ui.item ? ui.item.id : 0;
        if (test > 0)
        {
           alert(test);
        }
    }
});

5

这是带有示例AJAX调用的全新工作代码。

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>

<div>
    <div id="project-label">Select a project (type "j" for a start):</div>
    <img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
    <input id="project" />
    <input type="hidden" id="project-i" />
</div>


@*Auto Complete*@
<script>
    $(function () {

        $("#project").autocomplete({
            minLength: 0,
            source : function( request, response ) {
                $.ajax({
                    url: "http://jsonplaceholder.typicode.com/posts/1/comments",
                    dataType: "jsonp",
                    data: {
                        q: request.term
                    },
                    success: function (data) {
                        response( data );
                    }
                });
            },
            focus: function (event, ui) {
                $("#project").val(ui.item.label);
                return false;
            },
            select: function (event, ui) {
                $("#project").val(ui.item.name);
                $("#project-id").val(ui.item.email);                    

                return false;
            }
        })
            .data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                    .data("ui-autocomplete-item", item)
                    .append("<a> " + item.name + "<br>" + item.email + "</a>")
                    .appendTo(ul);
            };
    });
</script>

我看到您从ajax调用中得到了jsonp响应。回调函数的名称是什么?
米罗·莱顿宁

5

.ASPX页面上:

  <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head id="Head1" runat="server">
        <title>AutoComplete Box with jQuery</title>
        <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>  
        <script type="text/javascript">
            $(document).ready(function() {
                SearchText();
            });
            function SearchText() {
                $(".autosuggest").autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "Default.aspx/GetAutoCompleteData",
                            data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                            dataType: "json",
                            success: function (data) {
                                if (data != null) {

                                    response(data.d);
                                }
                            },
                            error: function(result) {
                                alert("Error");
                            }
                        });
                    }
                });
            }
        </script>
  </head>
  <body>
      <form id="form1" runat="server">
          <div class="demo">
           <div class="ui-widget">
            <label for="tbAuto">Enter UserName: </label>
       <input type="text" id="txtSearch" class="autosuggest" />
    </div>
        </form>
    </body>
    </html>    

在您的.ASPX.CS代码隐藏文件中:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        List<string> result = new List<string>();
            SqlConnection con = new SqlConnection("Data Source=YourDatasource;Initial Catalog=DatabseName;uid=sa;password=123");

            SqlCommand cmd = new SqlCommand("select DISTINCT Name from Address where Name LIKE '%'+@Name+'%'", con);
            con.Open();
                cmd.Parameters.AddWithValue("@Name", username);
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    result.Add(dr["Name"].ToString());
                }
                return result;
        }
}

1
@Jaikrat因为GET请求导致:“试图使用GET请求调用方法'GetAutoCompleteData',这是不允许的。” 请参阅:stackoverflow.com/questions/18703838/...
NickG

5

设置自动完成:

$("#searchBox").autocomplete({
    source: queryDB
});

获取数据的源函数:

function queryDB(request, response) {
    var query = request.term;
    var data = getDataFromDB(query);
    response(data); //puts the results on the UI
}

3

当您询问:

Blockquote //但是现在呢?如何显示我的数据?块引用

您需要这样映射一个对象数组:

response([{label: 'result_name', value: 'result_id'},]);

这样,当您使用自动完成插件的select事件时,可以看到下面的结果;

选择事件的结果

您可以通过以下方式使用select事件:

jQuery("#field").autocomplete({
      source: function (request, response) {

      },
      minLength: 3,
      select: function(event, ui)
      {
        console.log(ui);
      }
  });

我希望它可以帮助和补充答案。


0
$("#subject_name").autocomplete({
  source: function(request, response) {
    $.ajax({
      url: "api/listBasicsubject",
      dataType: "json",
      type: "post",
      data: {
        search: request.term
      },
      success: function(data) {

        if (!data.length) {
          var result = [{
            label: 'Subject not found',
            value: response.term
          }];
          response(result);
        } else {
          //response(data.data);
          response($.map(data.data, function(item) {
            return {
              label: item.subject_name,
              value: item.subject_id
            }
          }));
        }
      }
    });
  },
  change: function(event, ui) {
    if (ui.item == null) {
      $("#subject_name").val("");
      $("#subject_code").val("");
      $("#subject_name").focus();
    }
  },

  minLength: 0,
  classes: {
    "ui-autocomplete": "auto_compl-cat"
  },

  focus: function(event, ui) {
    event.preventDefault();
    // $("#subject_name").val(ui.item.label);

    $("#subject_name").val(ui.item.label);

  },

  select: function(event, ui) {
    if (ui.item.label == "Subject not found") {

      $("#subject_name").val('');
      $("#subject_code").val('');
      event.preventDefault();
      return false;
    }
    //console.log( "Selected: " + ui.item.label + " aka " + ui.item.value);
    $("#subject_name").val(ui.item.label);
    $("#subject_code").val(ui.item.value);
    return false;
  }
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.