我正在使用JQuery Ajax将POST变量发送到php,其中一些变量尚未定义,所以我声明它们并给它们null
,如下所示:
if ($(this).is('.filters')) {
alert("works");
}
else {
var type = status = bhk = null;
}
$.ajax({
method: 'POST',
url: '/search',
data: {
'do': getUrlParameter('do'),
'use': use,
'type': type, //null for now
'status': status, //null for now
'bhk': bhk, //null for now
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val(),
'page': page
}
}).done(function(data) {
if ($('#search').is(':visible'))
$('#search').hide();
var new_content = $(data).find('#search-filters, #scroll-to-list');
$( '#results' ).html( new_content );
$('html, body').animate({
scrollTop: $('#scroll-to-list').offset().top
}, 1000);
});
在php页面中,我声明并过滤它们:
$use = isset( $_POST['use'] ) ? (int) $_POST['use'] : ''; // int AJAX
$filter_type = isset( $_POST['type'] ) ? (int) $_POST['type'] : ''; // int AJAX
$filter_status = isset( $_POST['status'] ) ? (int) $_POST['status'] : ''; // int AJAX
$filter_bhk = isset( $_POST['bhk'] ) ? (int) $_POST['bhk'] : ''; // int AJAX
$filter_city = isset( $_POST['city'] ) ? (int) $_POST['city'] : 0; // int AJAX
$filter_zone = isset( $_POST['zone'] ) ? (int) $_POST['zone'] : 0; // int AJAX
$page_number = isset( $_POST['page'] ) ? (int) $_POST['page'] : ''; // int AJAX
我正在使用这些变量为MySQLi Select创建附加条件但是如果不是null则它们为0我得到一个错误:
if ($filter_type != NULL || $filter_type != '') {
$filter_type = 'AND t2.type = ' . $filter_type;
} else $filter_type = NULL;
if ($filter_status != NULL || $filter_status != '') {
$filter_status = 'AND t2.status = ' . $filter_status;
} else $filter_status = NULL;
if ($filter_bhk != NULL || $filter_bhk != '') {
$filter_bhk = 'AND t2.bhk = ' . $filter_bhk;
} else $filter_bhk = NULL;
if ($filter_city != 0) {
$filter_city = 'AND t2.city = ' . $filter_city;
$filter_zone = NULL;
if ($filter_zone != 0) {
$filter_zone = 'AND t2.zone = ' . $filter_zone;
}
} else $filter_city = $filter_zone = NULL;
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1
INNER JOIN property t2 ON t2.id = t1.id
WHERE t2.use = ?
' . $filter_type
. $filter_status
. $filter_bhk
. $filter_city
. $filter_zone . '
LIMIT ?, ?')) {
除此之外,还有更清洁或优化的方法吗?我很感激,谢谢!