我寫的是一個篩選的功能,我用ajax向php中的資料庫請求信息,並用JSON傳回給javascript,但是輸入相關內容時,有的篩選可以從資料庫中讀出來,有的就不行,想問怎麼解決。
javascript程式碼:
submitElement.addEventListener('click',function(event){
if(searchDescription === 1){
search = filterByTitleElement.value;
}else if(searchDescription === 2){
search = filterByDescriptionElement.value;
}
//将输入的搜索信息传递给php文件,让其再数据库中找到相应的匹配项。
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
a = eval('(' + xmlhttp.responseText + ')');
tableDisplay.innerHTML = a.length;
}
}
};
xmlhttp.open("GET", "SearchDeal.php?inputMessage=" + search + "&searchdescription=" + searchDescription, true);
xmlhttp.send();
});
function pageForDisplay(number){
var result = "<thead><tr><td>Search Result</td></tr></thead><tr><td><table border=\"1\" id=\"inside\">";
for(var i = 0; i < 5 ;i++){
result = result + " <tr><td><p class=\"photoInside\"><a href=\"DetailsPage.php\"><img src=\"travel-images/square-medium/" + a[number + i]['PATH'] +"\"></a>" +
"<h3><a href=\"DetailsPage.php\">" + a[number + i]['Title'] +"</a></h3>" +
"<p>" + a[number + i]['Description'] + "</p>" +
"</p></td></tr>";
}
result = result + "</table></td></tr>";
return result;
php程式碼:
$messageForSearch = $_GET["inputMessage"];
$messageForNumber = $_GET["searchdescription"];
$conn = mysqli_connect("localhost","root","","travel");
if($messageForNumber == 1){
$sql = "SELECT ImageID,Title,Description ,PATH FROM travelimage where Title REGEXP '[$messageForSearch]'";
}else if($messageForNumber == 2){
$sql = "SELECT ImageID,Title,Description ,PATH FROM travelimage where Description REGEXP '[$messageForSearch]'";
}
$a = mysqli_query($conn,$sql);
$json = mysqli_fetch_all($a,MYSQLI_ASSOC);
//print_r($json);
echo json_encode($json);
}
依照上面的程式碼,有的時候a.length會改變,但是有時就不會改變(一般是當篩選出來的結果太多時)。然而,如果我將php中的最後一行程式碼換成print_r($json)時,就會有輸出。
json要求使用utf8編碼,檢查資料庫取到的資料是否都是utf8編碼的。