【问题标题】:Mvc autocomplete ajaxMvc 自动完成 ajax
【发布时间】:2016-09-01 11:50:34
【问题描述】:

尝试:

$(document).ready(function () {
        $('#cityName').autocomplete({
            source: function(request,response) {
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Search", "City")',
                    dataType: 'json',
                    data: { name: request.term } ,
                    success: function (data) {
                        response($.map(data, function (item) {
                            alert(JSON.stringify(data));
                            alert(JSON.stringify(item.name));
                            return {
                                name: item.name, 
                                label: item.name
                            }
                        }));
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        })
    })

alert(JSON.stringify(data)) 得到这个:{"items":["Boston","Berlin"]}。 在alert(JSON.stringify(item.name)) 得到这个:未定义。

问题:它 (item.name) 是如何工作的?

【问题讨论】:

  • 试试items[0] - 数据是对象
  • 它有效,但仅适用于名字。
  • 你必须使用每个循环,遍历所有元素
  • 是的,但是你的ajax调用需要什么样的输出,如果它可以是一个字符串数组,你可以直接返回item
  • @Sousuke 这是一个字符串列表,但如果我尝试返回item,我会在同一行得到“波士顿,柏林”。

标签: ajax asp.net-mvc jquery-ui-autocomplete


【解决方案1】:

你只需要返回字符串数组:

$(document).ready(function () {
        $('#cityName').autocomplete({
            source: function(request,response) {
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Search", "City")',
                    dataType: 'json',
                    data: { name: request.term } ,
                    success: function (data) {
                        response(data.items);
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        })
    })

【讨论】:

  • 我明白了!非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
相关资源
最近更新 更多