我正在使用html输入“搜索”实现实时搜索,结果应显示在其下方,以便用户可以选择正确的名称。一旦客户选择名称,它将所选名称的ID分配给其他隐藏的输入“id”。以下是我的代码详细信息:
索引.php
<?php
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
var txt = $(this).val();
var resultDropdown = $(this).siblings(".result");
var personname = "";
var personID = "";
if (txt !='')
{
$.ajax
(
{
type:"post", //submit method
url: "search.php", //url to sumitted data To
data: {name : txt}, //Data to be submitted
cache: false,
dataType: 'json',
//action on successful post request
success: function(data)
{
//process JSON
$.each(data.names, function(idx, name){
var person = "<p>" + name.name +"</p>";
resultDropdown.html(person);
});
},
}
)
}
else
{
resultDropdown.empty();
}
});
// Set search input value on click of result item
});
</script>
</head>
<body>
<form method="post" action="result.php">
<div class="search-box">
<input type="text" id="search" autocomplete="off" name="spousename" placeholder="search spouse" />
<input type="hidden" id="id" autocomplete="off" name="spouseid" placeholder="search spouse" />
<input class="w3-button w3-block w3-green w3-section w3-padding" type="submit" name="access"><b>Login</b></button>
<div class="result"></div>
</div>
</form>
</body>
</html>
从搜索返回的数据.php
{"names":[{"name":" xxxxxx","id":3},{"name":"yyyy","id":6},{"name":"zzzz","id":5}]}
我面临的问题: 1- 结果滴落.html(人): 只显示 json 上的最后一项
2-如何在点击时分配ID
慕妹3242003
慕桂英3389331