我写的是一个筛选的功能,我用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)时,就会有输出。