【问题标题】:jQuery UI autocomplete doesn't do _renderItem in case ajax function sourcejQuery UI 自动完成在 ajax 函数源的情况下不执行 _renderItem
【发布时间】:2017-02-02 12:55:57
【问题描述】:

我使用 jQuery UI 创建了一个自动完成搜索字段。我可以毫无问题地使用该代码,它可以毫无问题地生成并以 HTML 格式显示结果。

但是,由于我在网站上使用了更多 AJAX 功能,并且不想分离 PHP 文件来对 MySQL 进行查询,因此我想通过自动完成功能发送 2 条数据。 1 是搜索词本身,另一个是我在 php 中的函数名称,因此它可以识别并找到正确的查询并返回数据。

使用这两个版本的代码,我可以在 chrome 的网络中看到 POST 是成功的,并且我从 PHP 获得了我的 json 编码的结果数组。

但是在版本 2 中,它不会使用 _renderItem 为其生成 HTML。

提前致谢!

$( "#newInit" ).autocomplete({
  source: function(request, response) {
        $.ajax({
            url: "search.php",
            type: "POST",
            dataType: "json",
            data: {
                term : request.term,
                f : "item_search"
            }
        });
  },
  minLength: 2,
  focus: function( event, ui ) {
    $( "#newInit" ).val( ui.item.name );
    return false;
  },
  select: function( event, ui ) {
    $( "#newInit" ).val( ui.item.name );
    $( "#newInit-id" ).val( ui.item.item_id );
    $( "#newInit-weight" ).html( ui.item.weight );
    $( "#newInit-icon" ).attr( "src", "images/" + ui.item.icon );

    return false;
  }
})
 .autocomplete( "instance" )._renderItem = function( ul, item ) {
  return $( "<li>" )
    .append( "<div>Name: " + item.name + "<br>Weight: " + item.weight + "<img width='30' height=30' src='http://url.com/" + item.icon + "'/></div>" )
    .appendTo( ul );
};

【问题讨论】:

  • 对于版本 2,检查来自 ajax 的响应。它真的会发送带有名称、重量和图标字段的项目列表吗?
  • 嗨,是的,我确实得到了以下格式的正确回复:[{"item_id":"4","name":"Tool","weight":"1.00"," Craftable":"0","last_mod":"0000-00-00 00:00:00","icon":""},{"item_id":"7","name":"Wool","重量":"0.10","craftable":"0","last_mod":"0000-00-00 00:00:00","icon":""}]

标签: jquery-ui


【解决方案1】:

将此添加到您的 ajax 函数中,这会将 ajax 响应传递给自动完成源。

      success: function( data ) {
        if(data) response( data );
        else response({});
      }

【讨论】:

  • 谢谢,这就是问题所在! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多