【问题标题】:Show image in JQuery ui autocomplete在 JQuery ui 自动完成中显示图像
【发布时间】:2018-01-21 13:33:48
【问题描述】:

我有一个完美运行的带有 JQuery ui 自动完成功能的脚本。有一个显示用户名字和姓氏的搜索过程。但是在我的数据库中,还有用户的图片,我想在建议中显示它,并带有名字和姓氏。

(在数据库中,pic包含图片url)

脚本:

$(function() {    
    $("#search").autocomplete({
        source: "autocomplete.php",
        minLength: 1,
        select: function(event, ui) {
            var url = ui.item.id;
            if(url != '') {
                location.href = '...' + url;
            }
        },   
        html: true,           
        open: function(event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);   			
        }
    });    	
});

autocomplete.php

<?php     
if ( !isset($_REQUEST['term']) ) {
	exit;
}
 
$mysqli = new MySQLi($DB_host,$DB_login,$DB_pass,$DB_select);
     
$term = trim(strip_tags($_GET['term'])); 
$term = preg_replace('/\s+/', ' ', $term);
 
$a_json = array();
$a_json_row = array();
 
$a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));
$json_invalid = json_encode($a_json_invalid);
 
if(preg_match("/[^\040\pL\pN_-]/u", $term)) {
  print $json_invalid;
  exit;
}

if ($data = $mysqli->query("SELECT * FROM users WHERE firstname LIKE '%$term%' OR lastname LIKE '%$term%' ORDER BY firstname , lastname")) {
	while($row = mysqli_fetch_array($data)) {
		$firstname = htmlentities(stripslashes($row['firstname']));
		$lastname = htmlentities(stripslashes($row['lastname']));
		$id= htmlentities(stripslashes($row['id']));
		$pic= htmlentities(stripslashes($row['pic']));
		$a_json_row["id"] = $id;
		$a_json_row["value"] = $firstname.' '.$lastname;
		$a_json_row["label"] = $firstname.' '.$lastname;
		array_push($a_json, $a_json_row);
	}
}
 
/* jQuery wants JSON data */
echo json_encode($a_json);
flush();
 ?>

请帮忙。

【问题讨论】:

    标签: javascript php jquery jquery-ui autocomplete


    【解决方案1】:

    您只需要准备好一个 &lt;img&gt; 元素即可接收 img URL...
    然后在选择时,将 URL 传递给 src 属性。

    在下面的演示中,我模拟了您的 json 响应....
    尝试使用“John Doe”或“System Admin”。

    $(function() {
      $("#search").autocomplete({
        source: //"autocomplete.php",
        [
          {
           id:"John Doe",
           value:"John Doe",
           label:"John Doe",
           img:"http://images.maskworld.com/is/image/maskworld/bigview/john-doe-foam-latex-mask--mw-117345-1.jpg"
          },
          {
           id:"System Admin",
           value:"system Admin",
           label:"system Admin",
           img:"http://www.ericom.com/imgs/braftonArticles/3-things-every-system-admin-should-know-about-virtualization_16001411_800906167_0_14057272_500.jpg"
          }
        ],
        minLength: 1,
        select: function(event, ui) {
          /*
          var url = ui.item.id;
          if(url != '') {
            location.href = '...' + url;
          }
          */
          var img = ui.item.img;
          $("#pic").attr("src",img);
        },
        html: true, 
        open: function(event, ui) {
           $(".ui-autocomplete").css("z-index", 1000);
        }
      });
    });
    img{
      max-height:350px;
      max-width:200px;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    
    <input type="text" id="search"><br>
    <img id="pic">


    编辑

    也许您希望在下拉菜单中显示图片...
    我在jQuery-UI documentation 找到了这个。

    $(function() {
    
          $("#search").autocomplete({
            source: //"autocomplete.php",
            [
              {id:"John Doe",
               value:"John Doe",
               label:"John Doe",
               img:"http://images.maskworld.com/is/image/maskworld/bigview/john-doe-foam-latex-mask--mw-117345-1.jpg"},
              {id:"system Admin",
               value:"system Admin",
               label:"system Admin",
               img:"http://www.ericom.com/imgs/braftonArticles/3-things-every-system-admin-should-know-about-virtualization_16001411_800906167_0_14057272_500.jpg"}
            ],
            minLength: 1,
            select: function(event, ui) {
              /*
              var url = ui.item.id;
              if(url != '') {
                location.href = '...' + url;
              }
              */
            },
            html: true, 
            open: function(event, ui) {
              $(".ui-autocomplete").css("z-index", 1000);
    
            }
          })
            .autocomplete( "instance" )._renderItem = function( ul, item ) {
            return $( "<li><div><img src='"+item.img+"'><span>"+item.value+"</span></div></li>" ).appendTo( ul );
          };
    
        });
    .ui-menu img{
      width:40px;
      height:40px;
    }
    .ui-menu li span{
      font-size:2em;
      padding:0 0 10px 10px;
      margin:0 0 10px 0 !important;
      white-space:nowrap;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    
    <input type="text" id="search"><br>

    【讨论】:

    • 感谢您的回答,但我想从数据库中获取图片。每个用户都有不同的个人资料图片。所以我想在建议中显示个人资料图片,然后是名字和姓氏。
    • 我的示例从自动完成请求的 json 中获取 img 源信息....所以来自您的数据库。
    • 所以我应该做类似的事情 $a_json_row["img"] = $pic;在 autocomplete.php 中?
    • 是的...您必须从 PHP 端发送 URL。我发现了一些你可能喜欢的东西......
    【解决方案2】:

    你可以使用_renderItem( ul, item )

    $("#search").autocomplete({
        source: [
            {
                value: "aaa",
                label: "aaa",
                desc: "aaa",
                icon: "https://dummyimage.com/50x50/000/fff&text=aaa"
            },
            {
                value: "bbb",
                label: "bbb",
                desc: "bbb",
                icon: "https://dummyimage.com/50x50/000/fff&text=bbb"
            },
            {
                value: "ccc",
                label: "ccc",
                desc: "ccc",
                icon: "https://dummyimage.com/50x50/000/fff&text=ccc"
            }
        ],
        minLength: 0,
        select: function (event, ui) {
            $("#search").val(ui.item.label);
            return false;
        }
    });
    $("#search").data("ui-autocomplete")._renderItem = function (ul, item) {
        return $('<li/>', {'data-value': item.label}).append($('<a/>', {href: "#"})
                .append($('<img/>', {src: item.icon, alt: item.label})).append(item.label))
                .appendTo(ul);
    };
    <link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
    <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
    
    
    <input type="text" id="search">

    【讨论】:

    • 感谢您的回答,但我想从数据库中获取图片。每个用户都有不同的个人资料图片。所以我想在建议中显示个人资料图片,然后是名字和姓氏。
    • php文件是autocomplete.php。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多