尝试使用jQuery.html();
从ajax响应中选择<ul>
列表中的<li>
时遇到问题
这是我的AJAX请求:
if (searchid != '') {
$.ajax({
type: "POST",
url: "/service/search.php",
data: dataString,
cache: false
}).done(function (html) {
$("#result").html(html).show();
var images = $("#result").find(".dbRows.sixth").html();
console.debug(images);
})
.fail(function (jqXHR, textStatus) {
$("#explainMessage").html('Unable to check at the moment. Please retry later').show();
})
}
return false;
在php中,我有这样的代码:
if ( mysqli_num_rows($result)==0)
{
$display = '<div id="explainMessage" class="explainMessage">Sorry, this was not found.</div>';
echo $display;
} else {
$counter = 0;
while ($row = $result->fetch_assoc()) {
++$counter;
$image_filename = $row['image_filename'];
$imageFolder = $_SERVER['DOCUMENT_ROOT'] . '/service/img/';
$imageList = scandir($imageFolder, 1);
$imageLink = '/service/img/' . $image_filename;
$withoutExt = preg_replace('/''.[^.''s]{3,4}$/', '', $image_filename);
$pattern = '/^(' . quotemeta($withoutExt) . ').*$/';
$display = '<div class="dbRows sixth" style="display:none"><ul>';
foreach ($imageList as $image) {
if (preg_match($pattern, $image)) {
if (in_array($image, $imageList)) {
$display .= '<li><img src="' . $imageLink . '" /></li>';
}
}
};
$display .= '</ul></div>';
echo $display;
问题是,当我尝试使用AJAX.done();
函数时,在我的控制台中,我只有<ul></ul>
,没有图像列表。我的问题是,为什么即使图像列表实际上在代码中,我也不能选择<ul>
标记中的代码?我是PHP的新手,任何帮助都将不胜感激。提前谢谢。
你做错了。正如我在询问您的响应HTML之前所怀疑的那样,您有空白"。
$("#result").find(".dbRows.sixth").html()
将只打印第一个匹配元素的html。
如果你想为所有匹配的元素获取html,可以试试这个:
$("#result").find(".dbRows.sixth").each(function(){
console.log($(this).html());
});
通过快速查看,我可以看到一些问题。在php中,将第一行代码从<div class="dbRows sixth" style="display:none"><ul>';
更改为$display = '<div class="dbRows sixth" style="display:none"><ul>';
我可能会把这个var images = $("#result").find(".dbRows.sixth").html();
改成这个var images = $("#result > .dbRows.sixth");
。
然后添加images.show();
和console.log(images.html());
。没有经过测试,但可能会让你走上正轨。