gpt4 book ai didi

javascript - 从 javascript 将数组发送到 PHP 函数并读取其值

转载 作者:行者123 更新时间:2023-12-03 06:46:51 26 4
gpt4 key购买 nike

我在 jQuery 中有一个 onclick 和 post 函数,我将两个变量传递给我的 PHP 函数。

函数如下所示:

$(".pop-save-us").click(function(){
console.log(checkbox_events);
console.log(user_id);
// alert("Button save pressed");
$.post('/user/AddRemoveBrandUsers', { brands: JSON.stringify(checkbox_events),userId:user_id} , function(data) {
if(checkbox_events.length==0)
{
alert("No changes were made.")
}
else {
if (data == "ok") {
alert("ok");
}
}
});

});

第一个值是以下格式的数组:

console.log(checkbox_events) 给出以下输出:

[2: "checked", 4: "checked", 5: "checked"]

我执行 `JSON.stringify(checkbox_events) 将数组转换为 JSON 格式并将其传递给我的 PHP 函数,如下所示:

 public function AddRemoveBrandUsersAction()
{
$brands = $this->getRequest()->getPost("brands");
$userId = $this->getRequest()->getPost("userId");
for($i=0;$i<count($brands);$i++)
{
// how can I now access each value of the brands array
// I need both key and value... How do I access them ??
}
die("ok");
}

最佳答案

使用以下代码:

 if(!empty($brands) && sizeof($brands) > 0){
foreach($brands as $key => $value){
...
}
}

关于javascript - 从 javascript 将数组发送到 PHP 函数并读取其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37700024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com