我有dataId
来自复选框值,我正在使用GET AJAX请求发送它:
dataId = 1, 2, 16, 15, 17, 3, 14, 5, 9, 11;
URI = "<?php echo site_url('Terpasang/Update_Kebutuhan_ke_Terpasang')?>";
$.ajax({
url : URI,
type: "GET",
data: { "iddata": [dataId] },
dataType: "JSON",
});
在控制器中,我使用代码传递此数据:
$iddata = array($_GET['iddata']);
$Countdata = count($iddata);
for($i = 0; $i <= $Countdata; $i++)
{
$data = array('id_perjal'=>$iddata[$i]); // this code can't generate id one by one like i wanna : 1, next 2, next 16 etc
$this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));
答案 0 :(得分:0)
问题在于如何构建阵列。您不能将变量设置为等于逗号值列表。如果您检查代码,则会发现dataId
只有一个值:
dataId = 1, 2, 16, 15, 17, 3, 14, 5, 9, 11;
data = {
"iddata": [dataId]
};
console.log(data);
&#13;
要解决此问题,请明确将dataId
定义为数组:
var dataId = [1, 2, 16, 15, 17, 3, 14, 5, 9, 11]; // note the [] wrapping the values
然后在您提供给data
的对象中使用它:
data: { "iddata": dataId },
答案 1 :(得分:0)
您需要首先为变量分配&#34; dataId&#34;那么它需要在你的ajax函数中传递dataId。您还可以在控制台日志中看到此成功信息。
var dataId=[1,2,16,15,17,3,14,5,9,11];
URI = "<?php echo site_url('Terpasang/Update_Kebutuhan_ke_Terpasang')?>";
$.ajax({
url : URI,
type: "GET",
data: {"iddata":dataId},
dataType: "JSON",
success:function(res){
console.log(res);
}
});
&#13;
您不需要在$ _GET [&#39; iddata&#39;]中添加数组。如果你想输入强制转换,那么只需添加(数组)$ _ GET [&#39; iddata&#39;]。如果您在数组中添加此$ _GET [&#39; iddata&#39;],那么您将得到您的计数1.
$iddata=$_GET['iddata'];
$Countdata=count($iddata);
for($i=0;$i<=$Countdata;$i++)
{
$data=array('id_perjal'=>$iddata[$i]); // this code can't generate id one by one like i wanna : 1, next 2, next 16 etc
$this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));
&#13;
答案 2 :(得分:0)
将dataId设置为字符串:
dataId = '1,2,16,15,17,3,14,5,9,11';// remove white space
URI = "<?php echo site_url('Terpasang/Update_Kebutuhan_ke_Terpasang')?>";
$.ajax({
url : URI,
type: "GET",
data: { "iddata": [dataId] },
dataType: "JSON",
});
在PHP代码中:
$iddata = explode(",",$_GET['iddata']);// string to array separated by ,
$Countdata = count($iddata);
for($i = 0; $i <= $Countdata; $i++)
{
$data = array('id_perjal'=>$iddata[$i]);
$this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));
答案 3 :(得分:0)
使用foreach
代替for
删除这些
$Countdata = count($iddata);
for($i = 0; $i <= $Countdata; $i++)
{
$data = array('id_perjal'=>$iddata[$i]); // this code can't generate id one by one like i wanna : 1, next 2, next 16 etc
$this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));
并添加
foreach($iddata as $id)
{
$data = array('id_perjal'=>$id);
$this->M_perjal_terpasang->save($data);
}