我想在PHP中創建一個基於AJAX的搜索。我迄今爲止編寫的代碼現在似乎沒有起作用。任何建議都會有很大的幫助。提前致謝。這是我的代碼。基於Ajax的搜索PHP
的index.php
<head>
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" name="text" id="text" autocomplete="off" onkeyup="showHint(this.value)"/>
<div id="inner"></div>
<script type="text/javascript">
function showHint(str) {
if(str.length == 0) {
document.getElementById('inner').innerHTML = "search";
return;
}
if(window.XMLHttpRequest) {
xmlhttp = XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttpreadystate == 4 && xmlhttp.status == 200) {
document.getElementById('inner').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("REQUEST", "search.php?text"+str, true);
xmlhttp.send();
}
</script>
</body>
</html>
的search.php
<?php
$host = 'localhost';
$user = 'root';
$password= 'root';
$db = 'demo';
@$conn = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db($db, $conn);
/*if($result) {
echo "success";
} else { echo "fail"; }
*/
$text = $_REQUEST['text'];
$text = preg_replace('#[^a-z0-9]#i', '', $text);
$query = "SELECT * FROM users where first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
$action = mysql_query($query);
$result = mysql_num_rows($action);
while($res = mysql_fetch_array($action)) {
$output .= $res['first_name']. ' '.$res['last_name'];
echo $output;
}
?>
定義 「不工作」。看看你的瀏覽器的開發者工具。看看JavaScript控制檯。它報告任何錯誤嗎?看看Net標籤。請求是否被提出?它會得到迴應嗎?它們是否包含您期望的數據? – Quentin 2015-02-09 07:25:03