php ajax autocomplete dropdownlist

时间:2014-11-08 11:37:30

标签: javascript php jquery ajax

我做了这个自动完成页面..我想当我点击ajax结果(电子邮件)时,第三个ajax页面显示用户名之类的东西,比如谷歌,当你开始输入并选择搜索你想让结果出现

index.php

<html> 
<head> 
<script src="jquery.js"></script> 
<link rel="stylesheet" href="style.css"/> 
</head> 
<body> 
<input type="text" name="search" id="live"/> <input type="submit" name="ok" value="Search"/> 
<div class="show"> 
<ul class="dropdown"> 

</ul> 

</div> 


<script> 
$( #live ).keyup(function(){ 


$.ajax({ 
type: "POST", 
url: "ajax.php", 
data:{"search":$("#live").val()}, 
success: function(msg){ 
$(".dropdown").html(msg); 
} 
}); 



}); 
</script> 
</body> 
</html> 

ajax.php

<?php 
$search=$_POST[ search ]; 
$connect=mysqli_connect("localhost","root","","candy"); 
$query=mysqli_query($connect,"SELECT * FROM users WHERE email LIKE $search% "); 
if(!empty($search)){ 
$num=mysqli_num_rows($query); 
if($num != 0){ 

while($row=mysqli_fetch_array($query)){ 

echo "<li class= result >$row[email]</li>"; 
} 
} 
else{echo "NO search result found"; } 

} 

?> 

result.php

我希望它显示所选电子邮件的用户名

2 个答案:

答案 0 :(得分:0)

.on()事件与

等下拉列表一起使用
// For dynamic Elements
$('.dropdown').on('click', 'li', function(){
    // Get the selected Email
    var email = $.trim($(this).text());

    // Send ajax request like you send before 
    // with email address and display result wherever required
    $.ajax({
        .........
    });
});

答案 1 :(得分:0)

为什么不将包含电子邮件的用户名作为隐藏数据发送?你的ajax.php中有类似的东西:

echo "<li class='result' data-username='$row[username]'>$row[email]</li>";

使用JQuery,您将能够获得此用户名属性:

$('.dropdown').on('click', '.result', function(){
    alert( $(this).attr('data-username') );
}