【问题标题】:JQuery Autocomplete won't autocompleteJQuery自动完成不会自动完成
【发布时间】:2015-01-17 12:05:21
【问题描述】:

我正在尝试编写我的第一个 jQuery 自动完成示例。我需要能够从自动完成中选择多个值,所以我使用了here 提供的示例。

无论我做什么,当我输入“c”、“ch”等时,我都无法让文本框显示值“chicken”和“chickens”。我做错了什么?

我的控制器有这个动作方法

public JsonResult GetBirds()
{
    var result = new JsonResult
        {
            Data = new
                {
                    Birds = new List<string> {"chicken", "chickens"}
                },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };

    return result;
}

而我的前端代码是这样的:

<script>
    $(function () {
        function log(message) {
            $("<div/>").text(message).prependTo("#log");
            $("#log").scrollTop(0);
        }

        $("#birds").autocomplete({
            source: "/Results/GetBirds",
            minLength: 1,
            select: function (event, ui) {
                log(ui ?
                "Selected: " + ui :
                "Nothing selected, input was " + this.value);
            }
        });
    });
</script>



<div class="demo">

    <div class="ui-widget">
        <label for="birds">Birds: </label>
        <input id="birds" />
    </div>

    <div class="ui-widget" style="margin-top:2em; font-family:Arial">
        Result:
        <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
    </div>

</div><!-- End demo -->

【问题讨论】:

    标签: c# jquery json jquery-autocomplete jsonresult


    【解决方案1】:

    使用 Rest Clint 或 Firebug Firefox 插件查看控制器返回的内容。

    试试这个:

    return Json(new {"chicken", "chickens"},JsonRequestBehavior.AllowGet);

    【讨论】:

    • 我使用了firebug,发现数据返回正确。问题是它在前端被错误地读取。
    【解决方案2】:

    您需要为每个对象构建一个包含“值”和“标签”的字典列表。

    http://api.jqueryui.com/autocomplete/

    【讨论】:

      【解决方案3】:

      您的来源格式不正确,忘记了 json 结果中的“Birds”键。就去吧:

      Data = new List<string> {"chicken", "chickens"}
      

      Data = new Dictionary<string, string> {
          {"chiken", "value1"},
          {"chikens", "value2"},
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-20
        • 2013-04-24
        • 2011-05-31
        • 1970-01-01
        • 2011-10-03
        • 2011-09-10
        • 2013-01-14
        相关资源
        最近更新 更多