我有一個<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();
});
});