我创建了以下搜索表单,没有任何错误,但我没有显示与搜索词类似的行,而是从数据库中的选定表中获取整个行列表我不确定为什么?
HTML
<div class="form-horizontal">
<fieldset>
<legend>Search</legend>
<div class="form-horizontal">
<div class="col-sm-10">
<input id="search-form" name="search" type="text" placeholder="Start searching here..." class="form-control">
</div>
<div class="col-sm-2">
<button class="btn btn-primary" id="searchButton" onclick="searchForm()">Search</button>
</div>
</div>
</fieldset>
</div>
<br/>
<table class="table" id="search-results" style="display:none;">
<thead>
<tr>
<th>Name</th>
<th>Serial</th>
<th>Barcode</th>
</tr>
</thead>
<tbody id="search-body">
</tbody>
</table>
</div>
JS
function searchForm(){
var d = $("#search-form").val();
if(d != "") {
$.ajax({
type: 'POST',
url: 'http://www.test.co.uk/test/search.php',
crossDomain: true,
data: {data: d},
dataType: 'json',
async: false,
success: function (response){
if (response.success)
{
$('#search-results').show();
$.each(response.data, function( index, item ) {
$('#search-body').append('<tr><td>' + item.name + '</td><td>' + item.barcode + '</td><td>' + item.serial + '</tr>');
});
}
else {
console.log("fail");
}
},
});
}
else {
alert("You must enter a term");
}
return false;
}
PHP
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("test");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
$num = mysql_num_rows($sql);
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
while ($row = mysql_fetch_array($sql))
{
$json['data'][]=array('name'=>$row['name'], 'barcode'=>$row['barcode'], 'serial'=>$row['serial']);
}
}
else
{
$json['success'] = FALSE;
}
echo json_encode($json);
?>
答案 0 :(得分:1)
更改jquery代码
data:{search: d}
说明:
您通过ajax
发送了名为data
的搜索查询。但是在php中你正在检查
isset($_post['search'])
您可以更改您的jquery代码或更改php
isset($_post['data'])
答案 1 :(得分:0)
将Jquery中的成员名称从数据更改为搜索。
data: {search: d},
因为您要发送会员&#34;数据&#34;并寻找&#34;搜索&#34;。