【发布时间】:2020-06-28 19:16:32
【问题描述】:
我有一个带有 else 语句的 PHP 页面,它通过用户输入从 SQL 数据库中过滤掉数据;这是一些伪代码:
NextPage.php
//Include database configuration file
include('../dbConfig.php');
if(isset($_POST['pageno']) || isset($_POST['FetchFilters'])) {
$limit = 10;
$pageno = $_POST['pageno'];
$offset = !empty($pageno) ? $pageno: 1;
$SQL = "
SELECT * FROM list WHERE wt >= 2.5
";
if($pageno >= 1) {
if(isset($_POST["shape"])) {
$shape_filter = implode("','", $_POST["shape"]);
$SQL .= "
AND stoneshape IN('".$shape_filter."')
";
}
if(isset($_POST["color"])) {
$color_filter = implode("','", $_POST["color"]);
$SQL .= "
AND stonecolor IN('".$color_filter."')
";
}
$SQL .= "
ORDER BY wt ASC
LIMIT
$offset,
$limit
";
$result = mysqli_query($db, $SQL);
$output = '';
if(isset($_POST["shape"]) && isset($_POST["color"]) && $row = mysqli_fetch_array($result)) {
while($row = mysqli_fetch_array($result)) {
$output .= '
<div class="Listing">
<!-- landing page -->
<a href="#ItemPage" class="ItemLink">
//Item Information goes here
</a>
</div>
';
}
}
} else {
$output = '
<h1 class="Error">
NO DATA MATCHES THAT
</h1>
';
}
echo $output;
}
?>
然后我有一个 AJAX 调用,当图像(inView 中的 ID 为#Loader)时分页;这是它的伪代码:
InfiniteScroll.js
$(document).ready(function(){
$('#Loader').on('inview', function(event, isInView) {
if (isInView) {
//Pagination
var nextPage = parseInt($('#pageno').val()) + 1;
//Filters
var shape = get_filter('shape');
var color = get_filter('color');
$.ajax({
type: 'POST',
url: 'vendors/php/NextPage.php',
data: {
pageno: nextPage,
shape: shape,
color: color
},
async: true,
cache: false,
error:
function(jqXHR, strError) {
if(strError == 'timeout') {
// Do something. Try again perhaps?
alert('Seems like there was an error loading the next page.');
}
},
success:
function(data) {
$('#Container').append(data); //Container where the NextPage.php data appends to
$('#pageno').val(nextPage);
if(data != '') { //Here is where my question lyes
$('.Error').hide(); //Else statement on NextPage.php should 'hide' as there is data to show
$('#Loader').show(); //Show image for pagination
} else {
$('.Error').show(); //Else statement on NextPage.php should 'show' as there is data to show
$('#Loader').hide(); //Hide image for pagination
}
},
timeout: 3000
});
}
});
});
//Gets values of filters for filters variables
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function() {
filter.push($(this).val());
});
return filter;
}
我的问题是 NextPage.php 上的 else 语句被视为数据,所以我不知道如何检查 $row 是否正在显示。当有$row(s) 显示其他hide #Loader 和show .Error 时,我希望.Error 类为hide。如何在我的 AJAX 调用中检查 .Error?
【问题讨论】:
-
您应该考虑将数据返回为 JSON,而不是 HTML。然后使用模板将其添加到站点。要返回错误检查此stackoverflow.com/questions/4417690/…
-
您的 SQL 容易受到 SQL 注入攻击。您应该使用参数化查询,因为您已经在使用 mysqli。
-
@scragar 解决这个问题后,我将使用this 教程帮助我设置参数。我只是不喜欢同时处理两个问题。这让我很困惑哈哈
-
@ariel 出于好奇(我对这一切都很陌生)将数据返回为 HTML 有什么问题?
标签: javascript php jquery ajax pagination