![](/img/trans.png)
[英]Dynamic dropdown list, pagination and search bar with Ajax/PHP/JQuery
[英]PHP, ajax, xml, jQuery - Dynamic search only returns one value
我正在嘗試在html,jQuery,ajax和php中實現動態搜索功能。 問題在於搜索功能僅在您輸入2-3個字母時才進行搜索。 例如:當按下字母“ f”時,它將返回數據庫中包含字母“ f”的每一行。 返回數據為空。(它應該返回20個值,我已經測試過查詢)現在,它僅在寫入“ foo”時返回結果,也許是因為那是唯一具有名稱的行。 這次返回的是xml結構:
<picture>
<picuser>CorrcetUser</picuser>
<picurl>CorrectURL</picurl>
<pictime>CorrectTime</pictime>
<picid>CorrectID</picid>
<comment>
<commenttime>Foo</commenttime>
<commentuser>Foo</commentuser>
<commenttext>Foo</commenttext>
</comment>
<description>
Foo bar
</description>
</picture>
現在是下面的代碼:
javascript文件
$(document).ready(function() {
$(".search").keyup(function() {
var searchbox = $(this).val(); // get the string in the searchbox
var dataString = 'searchword=' + searchbox;
if (searchbox == '') {
} else {
$.ajax({
type : "POST",
url : "search.php",
data : dataString,
dataType : "xml",
async: false,
cache : false,
success : function(data, textStatus, jqXHR) {
//Data repsonse from server
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
}
});
});
這是search.php
<?php
include ('dbconnect.inc.php');
if ($_POST) {
echo '<?xml version="1.0" standalone="no"?>';
$searchword = $_POST['searchword'];
$sql = "SELECT * FROM picture WHERE description LIKE :searchword";
$query = $dbh -> prepare($sql);
$query -> execute(array('searchword' => '%' . $searchword . '%'));
$nr=0;
$outputXML ="";
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$outputUser = $row['userName'];
$outputPicURL = $row['picURL'];
$outputTime = date('Y-m-d H:i', $row['time']);
$outputString = $row['description'];
$outputPicID = $row['pictureID'];
$outputXML.= "<picture>
<picuser>$outputUser</picuser>
<picurl>$outputPicURL</picurl>
<pictime>$outputTime</pictime>
<picid>$outputPicID</picid>
<comment>
<commenttime>Foo</commenttime>
<commentuser>Foo</commentuser>
<commenttext>Bar</commenttext>
</comment>
<description>
Foo bar
</description>
</picture>";
}
echo $outputXML;
}
?>
我以為這是一個簡單的解決方法,但是在這里我陷入了困境。 想知道為什么數據為空?
Xml文檔只需要一個根元素。 您需要輸出:
if ($_POST) {
header('Content-type: application/xml');
echo '<?xml version="1.0" standalone="no"?>';
echo '<pictures>';
...
foreach($results as $row) {
$outputUser = htmlspecialchars($row['userName']);
...
}
echo '</pictures>';
}
如果提供了XML內容類型( header('Content-type: application/xml');
),則某些瀏覽器(如IE)只會將響應解析為DOM。
如果使用字符串函數(如echo
)在xml中輸出值,則需要轉義值( htmlspecialchars()
)。 否則, <
或&
類的字符可能會破壞您的xml。
最后,如果您將XML作為Javascript中的字符串獲取,則可以創建DOMParser
並使用它來解析它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.