【问题标题】:jQuery Autocomplete Not Showing Results on Client-SidejQuery自动完成未在客户端显示结果
【发布时间】:2016-07-08 03:04:21
【问题描述】:

我的结果没有填充到由 jQuery UI 提供支持的自动完成中。我只是在搜索栏下方看到空行,有时它们甚至没有出现。

当我在搜索字段中键入字符时,我确实在控制台窗口中看到了我的结果。我不知道我做错了什么。

我的客户端代码是这样设置的:

<input id="autocomplete" class="form-control input-lg" name="autocomplete" placeholder="Search an address" type="text">

$('#autocomplete').autocomplete({
  source: function(request, response) {
    $.getJSON('{{url_for("getInfo")}}', {
      a: request.term,
    }, function(data) {
      console.log(data);
      response(data.addresses);
    });
  },
  minLength: 3,
  select: function(event, ui) {
    console.log(ui.item.value);
  }
});

我可以从console.log(data); 行看到结果。它返回一个包含 3 项数组的对象:Object {addresses: Array[3]}

我使用 Flask 的服务器端代码是这样设置的:

@app.route('/getInfo', methods=['GET'])
def getInfo():
    address = request.args.get("a")
    addressCollection = myDB["addresses"]
    addressJSON = []

    for address in addressCollection.find({'Address': {'$regex':regex,'$options':'i'} },{"Address":1,"_id":0}).limit(3):
        addressJSON.append({"Address":address["Address"]})
    return jsonify(addresses=addressJSON)

结果如下:

{
  "addresses": [
    {
      "Address": "29 Valleyridge Rd",
    }, 
    {
      "Address": "29 Valleyview Dr", 
    }, 
    {
      "Address": "29 Valleystone Cr",
    }
  ]
}

【问题讨论】:

    标签: jquery jquery-ui flask autocomplete jquery-ui-autocomplete


    【解决方案1】:

    jQuery UI 自动完成source 需要一个字符串数组,或者一个具有labelvalue 属性的对象数组。所以你应该相应地转换你的数据。你的成功回调应该是这样的:

    function(data) {
      var transformed = data.addresses.map(function(address) {
        return address.Address;
      });
      response(transformed);
    }
    

    或者

    function(data) {
      var transformed = data.addresses.map(function(address) {
        return {
          label: address.Address
        };
      });
      response(transformed);
    }
    

    【讨论】:

    • 感谢您的澄清。这个解决方案效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多