javascript - 通过php向js发送两个变量
问题描述
我有
$userPostsInt = array("22", "45", "56");
我通过 ajax 收到一个 id:
$post_id = $_POST['id'];
然后在前端我单击并发送一个 ID,我需要检查是否:
1. the clicked ID is in the array
2. if the array count is <= 2 if not do something
所以我尝试:
$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);
if($count<2) {
foreach($userPostsInt as $key=>$post){
if( $post == $post_id ) {
foreach($userPostsInt as $idInt){
array_push($totSaved, $idInt);
}
echo json_encode($count);
}
}
} else {
echo json_encode($count);
}
然后在ajax成功我做:
success: function(data) {
var received = true;
if(received) {
if(data < 2) {
do_something
} else {
do_something
}
} else {
do_something else
}
}
如何发送 2 个变量以对“数组中是否有 ID?数组是否小于 2?”echo json_encode($count);
进行双重检查?还是我错过了另一种方式?
解决方案
简单的方法是in_array()
与数组输出一起使用:
$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);
if(in_array($post_id,$userPostsInt)){
echo json_encode(array('found'=>'yes','count'=>$count));
}else{
$totSaved[] = $post_id;//add new value for next time checks
echo json_encode(array('found'=>'no','count'=>$count));
}
推荐阅读
- java - NullPointerException - getCellTpeEnum() POI
- php - 当 2 个产品来自不同类别时,更改 woocommerce 购物车页面中的“数量”文本
- java - 如何为 JMX 和 Java 任务控制导入 lib?
- html - 使用 CSS 关键帧显示一个又一个内容
- python - 从 C 代码序列化数组数据,在 Python 中反序列化
- angular - 角度 6+。如何扩展模板添加新的动作,如 JSF?
- security - 从 PGP 签名中看出哪些算法在其创建过程中起作用
- python - Pandas DataFrame 中的交叉表
- d3.js - c3.js - 隐藏特定数据集的工具提示
- node.js - 错误:ffmpeg 以代码 1 退出:未找到选项帧速率