【发布时间】:2018-09-13 11:08:04
【问题描述】:
我使用 javascript、json、ajax、mysql 制作了一个简单的实时搜索引擎。我认为一切正常。但是当我搜索类似的东西时 - c++, c# 它什么也没显示。请帮我。这是我的代码:
<input type="text" id="search" class="form-control" placeholder="Enter your book name..." onkeyup="loadDoc()"/>
<div id="resultView"></div>
var ajaxRequest;
函数 ajaxFunction(){
try{
ajaxRequest = new XMLHttpRequest();
}catch(e){
try{
ajaxRequest = new ActiveXObject("Msxm12.XMLHTTP");
}catch(e){
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("Your browser need to update!");
return false;
}
}
}
}
函数 loadDoc(){ ajaxFunction();
manipulateFunction(ajaxRequest);
}
函数操作函数(xhttp){
var searchWord = document.getElementById('search').value;
console.log(searchWord);
var queryString = '?searchString=' + searchWord;
console.log(queryString);
var resultArea = document.getElementById('resultView');
if(!searchWord.replace(/\s/g, '').length){
resultArea.innerHTML= "Please search something valid...";
}else{
xhttp.open("GET",'search.php'+ queryString,true);
xhttp.onreadystatechange = function(){
if(xhttp.readyState === 4 && xhttp.status === 200){
var data = JSON.parse(xhttp.responseText);
console.log(data);
if(data.length > 0){
var html = "<table border='1px'>";
html += "<tr>"
html += "<th>ID</th><th>Name</th><th>Author Name</th><th>Category</th><th>Price</th>";
html += "</tr>";
for(i=0; i<data.length; i++){
var bookId = data[i].book_id;
var bookName = data[i].book_name;
var bookAuthor = data[i].book_author;
var bookCategory = data[i].book_category;
var bookPrice = data[i].book_price;
html +="<tr>";
html += "<td>" + bookId + "</td><td>" + bookName + "</td><td>" + bookAuthor + "</td><td>" + bookCategory + "</td><td>" + bookPrice + "</td>";
html += "</tr>";
}
html += "</table>";
resultArea.innerHTML = html;
}else{
resultArea.innerHTML = "Sorry No Result found in our database!";
}
}else{
resultArea.innerHTML = "Waiting for server response....";
}
}
xhttp.send();
}
}
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=book_db", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_GET['searchString'])){
$searchItem = $_GET['searchString'];
$query = "SELECT * FROM book_details WHERE book_name like '%$searchItem%'";
$STH = $db->查询($查询);
$STH->setFetchMode(PDO::FETCH_OBJ);
$someData = $STH->fetchAll();
echo json_encode($someData);
}
}catch(PDOException $error){
echo "<pre>";
echo $error;
echo "</pre>";
}
?>
【问题讨论】:
标签: javascript mysql json ajax