【发布时间】:2019-03-18 03:35:48
【问题描述】:
美好的一天,我正在尝试检查从 ajax 传递的某些变量的值是否不为空。我已经在 jQuery (ajax) 中验证了这一点,但试图在 php 中添加一个额外的层来检查 $_POST 值是否不为空。以下是变量;
$_smChest = wp_strip_all_tags( $_POST['send_smChest'] );
$_smSleeve = wp_strip_all_tags( $_POST['send_smSleeve'] );
$_smShoulder = wp_strip_all_tags( $_POST['send_smShoulder'] );
$_smJacketLength = wp_strip_all_tags( $_POST['send_smJacketLength'] );
$_smArmHole = wp_strip_all_tags( $_POST['send_smArmHole'] );
$_smBicep = wp_strip_all_tags( $_POST['send_smBicep'] );
$_smStomach = wp_strip_all_tags( $_POST['send_smStomach'] );
$_smFrontWidth = wp_strip_all_tags( $_POST['send_smFrontWidth'] );
$_smBackWidth = wp_strip_all_tags( $_POST['send_smBackWidth'] );
$_smWaistBand = wp_strip_all_tags( $_POST['send_smWaistBand'] );
$_smPantsLength = wp_strip_all_tags( $_POST['send_smPantsLength'] );
$_smSeat = wp_strip_all_tags( $_POST['send_smSeat'] );
$_smStride = wp_strip_all_tags( $_POST['send_smStride'] );
$_smthighs = wp_strip_all_tags( $_POST['send_smthighs'] );
$_smKnee = wp_strip_all_tags( $_POST['send_smKnee'] );
$_smLegOpening = wp_strip_all_tags( $_POST['send_smLegOpening'] );
$_smJacketFit = wp_strip_all_tags( $_POST['send_smJacketFit'] );
$_smTrouserFit = wp_strip_all_tags( $_POST['send_smTrouserFit'] );
我看到了这个问题(PHP Check if all variables are empty) 并使用此代码检查变量的值是否不为空;
$user = wp_get_current_user();
if (!empty($_POST)) {
foreach ($_POST as $value) {
if (!empty($value)) {
//Then Updated the users profile with the value and echo 1 for Ajax Response
update_user_meta( $user->ID, 'sm_chest', $_smChest);
update_user_meta( $user->ID, 'sm_sleeve', $_smSleeve);
update_user_meta( $user->ID, 'sm_shoulder', $_smShoulder);
update_user_meta( $user->ID, 'sm_jacket_length', $_smJacketLength);
//(...)
echo '1';
}else {
// echo '0' for Ajax response
echo '0';
}
}
}
当我这样做时,用户配置文件得到了更新,这很好,但 ajax 响应是 11111111111111111110 而不是 1 [见下图]
我知道我可以使用这样的东西[下面的代码],但是 if 语句会很长。这就是为什么我希望使用更优化的方法
if (!empty($_smChest) && !empty($_smSleeve) && !empty($_smShoulder) && !empty($_smJacketLength) && //(...) ) {
//Then Updated the users profile with the value and echo 1 for Ajax Response
update_user_meta( $user->ID, 'sm_chest', $_smChest);
update_user_meta( $user->ID, 'sm_sleeve', $_smSleeve);
update_user_meta( $user->ID, 'sm_shoulder', $_smShoulder);
update_user_meta( $user->ID, 'sm_jacket_length', $_smJacketLength);
//(...)
echo '1';
}else {
echo '0';
}
不知道我做错了什么或者为什么我得到很多1s 和0。
我想要实现的是;
1. 遍历每个变量的所有值,确保没有一个为空;
2. 使响应返回1或0,如果值分别为非空或空
非常感谢我可以做些什么来完成这项工作的想法。
【问题讨论】:
-
在 for 循环中,如果为真,则在回显
1,如果为假,则回显0。在每次迭代中,它都会将1或0打印到响应的正文中。 -
是的,我在循环中回显
1如果为真,如果为假,则为0,但在图像中看到的响应中打印了0,这意味着某处有问题。我真的很喜欢回复1是否有/没有空值和0如果有/有空值 -
您是否尝试过输出值而不是 0 以查看发生了什么以及发生的位置和原因?
-
我刚刚在您回复@Blu3 之前尝试过,将
1更改为Yes并将0 更改为No,我得到了Yes0的回复...不知道为什么@987654346 @已添加 -
我的意思是尝试回显变量 post 以查看它给你什么,不要回显除了帖子的值之外的任何特定内容