我有一个<input>
,当有人输入时显示建议。我正在构建后端,以便ajax抓取数据库中前五个具有该字母序列的标记,并以跨度显示它,特别是<div>
。我似乎并没有完全成功。这是我做过的第一个Ajax。帮助将不胜感激。以下是适用的HTML,Javascript和PHP。我认为我很接近,但不确定如何继续。该问题可能是在JavaScript中。在php和jQuery中使用ajax时,如何循环浏览json?
HTML:
<label id="testTagsLabel">Tags:</label>
<input type="text" name="tags" id="testTags" placeholder="Ex: Poem, Edgar Allen Poe">
<div id="tagSuggest">
<ul>
<!--the javascript would add the suggests as list items here-->
</ul>
</div>
PHP:
<?php #create_set.ajax.php
$tagSuggestions = array();
$currentTag = $_POST['sendTag'];
if (!empty($currentTag)){
require_once (MYSQL); //gets the database connection
$enteredTag = mysqli_real_escape_string ($dbc, $currentTag);
$q = "SELECT name FROM tags WHERE MATCH(name) AGAINST('$enteredTag'.'*' IN BOOLEAN MODE) LIMIT 5";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) > 0) {//if there are tags that match what the user typed
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$tag = $row['name'];
$tagSuggestions[] = $tag;
}
echo json_encode($tagSuggestions);
}
}
?>
的Javascript:
$(function(){
function sendTag(str){
$.post("../includes/create_set.ajax.php",{ sendTag: str },
function(data){
for (var key in data.returnTag) {
if(data.returnTag.hasOwnProperty(key)) {
$('#tagSuggestTag').html('<li class="tagSuggestTag">' + data.returnTag + "<li>");
}
}
}, "json");
}
$('#testTags').keyup(//on key press in tag field show the send the request and show the suggestions
function(){
sendTag($(this).val());
$('#tagSuggest').show();
});
});