所以我有4个名为$description,$hscode,$from,$to
的php变量我希望通过AJAX请求发送这些变量。我的不完整尝试是这样的:
function searchFilter(page_num) {
page_num = page_num?page_num:0;
$.ajax({
type: 'POST',
url: 'getData.php',
data: { page : +page_num, "desc" : "<?php print $description ?>","hscode" : "<?php print $hscode ?>","from" : "<?php print $from ?>","to" : "<?php $to ?>" },
beforeSend: function () {
$('.container-fluid').waitMe({
effect : 'stretch',
bg : 'rgba(255,255,255,0.7)'
});
},
success: function (html) {
$('#posts_content').html(html);
$('.container-fluid').waitMe("hide");
}
});
}
问题是,PHP变量是动态的意味着它们并不总是在某个时间设置$description
,有时只设置$hscode
,有时仅$description
和$hscode
设置,此类型有6种组合。请在这种情况下帮助我如何发送此请求。
可能答案:
代码工作正常,但我很困惑,这是一个正确的方法,请纠正我,如果我错了,我的工作代码是:
function searchFilter(page_num) {
page_num = page_num?page_num:0;
$.ajax({
type: 'POST',
url: 'getData.php',
data : { page : +page_num,
<?php if(isset($description)){ echo '"desc"'.' : '. "'$description'" . ',';} ?>
<?php if(isset($hscode)){ echo '"hscode"'.' : '. "'$hscode'" . ',';} ?>
<?php if(isset($from)){ echo '"from"'.' : '. "'$from'" . ',';} ?>
<?php if(isset($to)){ echo '"to"'.' : '. "'$to'" . ',';} ?> },
beforeSend: function () {
$('.container-fluid').waitMe({
effect : 'stretch',
bg : 'rgba(255,255,255,0.7)'
});
},
success: function (html) {
$('#posts_content').html(html);
$('.container-fluid').waitMe("hide");
}
});
}
答案 0 :(得分:1)
首先,您可以检查您的变量是否已设置,如果其设置已开启; y将这些变量附加到ajax数据。请尝试以下代码:
function searchFilter(page_num) {
page_num = page_num?page_num:0;
send_data = {};
send_data.page = +page_num;
<?php if (isset($description)): ?>
send_data.desc = "<?php echo $description ?>";
<?php endif; ?>
<?php if (isset($hscode)): ?>
send_data.hscode = "<?php echo $hscode ?>";
<?php endif; ?>
<?php if (isset($from)): ?>
send_data.from = "<?php echo $from ?>";
<?php endif; ?>
<?php if (isset($to)): ?>
send_data.to = "<?php echo $to ?>";
<?php endif; ?>
$.ajax({
type: 'POST',
url: 'getData.php',
data: send_data,
beforeSend: function () {
$('.container-fluid').waitMe({
effect : 'stretch',
bg : 'rgba(255,255,255,0.7)'
});
},
success: function (html) {
$('#posts_content').html(html);
$('.container-fluid').waitMe("hide");
}
});
}
答案 1 :(得分:1)
为了清楚起见,在PHP中组装数组,然后使用json_encode()
将其转换为JSON对象:
<?php
$php_data = [desc => $description, /* initialize other fields */];
?>
function searchFilter(page_num) {
var data = <?php= json_encode($php_data) ?>; /* dump as JSON object */
data.page_num = page_num?page_num:0; /* assign page_num field */
$.ajax({
type: 'POST',
url: 'getData.php',
data: data, /* pass object */