jQuery PHP Mysql jSon显示循环中的数据
我有使用jSon的jQuery Ajax Autosuggest。jQuery PHP Mysql jSon显示循环中的数据
现在我在显示数据时遇到了问题。数据使用PHP(循环数据)从mysql数据获得,但是当得到结果时,它总是显示1行。
这里是我的js代码:
$.ajax(
{
type: "GET",
data: post_string,
dataType: "json",
cache: false,
url: 'search.php',
success: function(data)
{
full_name = data[0].full_name;
username = data[0].username;
$("#divResult").show();
$(".display_box").html(username);
}
});
和search.php中
$getSearchWord = mysqli_real_escape_string($con, $_GET['searchword']);
$json = array();
$searchQuery = mysqli_query($con, "SELECT * FROM tb_users WHERE username LIKE '%$getSearchWord%' OR full_name LIKE '%$getSearchWord%' LIMIT 5");
while($searchFetchData = mysqli_fetch_array($searchQuery))
{
$json[] = array(
'username' => $searchFetchData['username'],
'full_name' => $searchFetchData['full_name']
);
}
echo json_encode($json);
和HTML DIV显示
<div id="divResult">
<div class="display_box"></div>
</div>
的Json
要清除出领域,在Aja之前打电话给这个X请求:
$("#divResul").hide(200);
$(".display_box").html('');
你可以尝试把它放在你的面前.display_box
运行所有返回数组。获取从search.php
返回的数组长度,然后在循环中运行它。
success: function(data){
$("#divResult").show(200);
var n = data.length;
for(var x = 0; x < n; x++){
$(".display_box").append(data[x].full_name);
$(".display_box").append(data[x].username);
}
}
没有的Json
OR不使用json
。从你的search.php:
$table = '<table>';
$getSearchWord = mysqli_real_escape_string($con, $_GET['searchword']);
$json = array();
$searchQuery = mysqli_query($con, "SELECT * FROM tb_users WHERE username LIKE '%$getSearchWord%' OR full_name LIKE '%$getSearchWord%' LIMIT 5");
while($searchFetchData = mysqli_fetch_array($searchQuery))
$table .= '<tr>
<td>'.$searchFetchData['username'].'</td>
<td>'.$searchFetchData['full_name'].'</td>
</tr>';
}
$table .= '</table>';
echo $table; /* RETURN THIS TO YOUR AJAX REQUEST */
然后在您的Ajax请求:
$.ajax(
{
type: "GET",
data: post_string,
url: 'search.php',
success: function(data)
{
$("#divResult").show(200);
$(".display_box").html(data);
}
});
嗨,谢谢你的回答。但我需要它使用jSon。你能帮忙吗? –
@HiDayurieDave - 检查我更新的答案。 –
尝试了代码,工作但会随时追加我输入的所有内容。 –
在AJAX发送这样的数据,它可以为你工作
$.ajax(
{
type: "GET",
data : { searchword: "keyword"},
dataType: "json",
cache: false,
url: 'search.php',
success: function(data)
{
full_name = data[0].full_name;
username = data[0].username;
$("#divResult").show();
$(".display_box").html(username);
}
});
请试试这个你成功回调。你所需要的只是迭代$.each()
并追加到div。
success: function(data)
{
$.each(data,function(index,value) {
full_name = value[0].full_name;
username = value[0].username;
$(".display_box").append(username . '<br/>');
})
$("#divResult").show();
}
因为你只试图把第一个索引'[0]'返回的数组。 –
那么我怎样才能把索引中的所有数据? –