我有一些问题。首先,我想将我的数据存储到数组集合的数组中。然后将数据传递给 Controller 提交。这是我的代码
Ajax.php
$("#submit").click(function() {
var total = 3;
var photos = new Array();
for(var i = 0; i < total; i++)
{
photos[i] = $('#thumbnail'+i+'').children('img').attr('src');
var collection = {
'no' : i,
'photo' : photos[i]
};
}
$.ajax({
type: "POST",
url: "<?php echo base_url()?>create/submit",
data: {collection : collection},
cache: false,
success: function(response)
{
console.log(response);
alert('success');
window.location = '<?php echo base_url()?>create/submit';
}
});
});
[编辑]
Controller
function submit()
$collection = $this->input->post('collection');
print_r($collection);
if(is_array($collection)) {
foreach ($collection as $collect) {
echo $collect['no'];
echo $collect['photo'];
}
}
else
{
echo 'collection is not array!';
}
}
结果
collection is not array!
基于 PeterKa 解决方案,我在我的控制台中得到了这个 在控制台中
Array
(
[0] => Array
(
[no] => 0
[photo] => https://scontent.cdninstagram.com/hphotos-xap1/t51.2885-15/s320x320/e15/11176494_1106697872689927_2104362222_n.jpg
)
[1] => Array
(
[no] => 1
[photo] => https://scontent.cdninstagram.com/hphotos-xfa1/t51.2885-15/s320x320/e15/11376044_838742186174876_410162115_n.jpg
)
[2] => Array
(
[no] => 2
[photo] => https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s320x320/e15/11381470_878168042272606_1132736221_n.jpg
)
)
但是,我的 Controller 中的结果并不像预期的那样。
最佳答案
collection
变量是循环的局部变量,并不包含您迭代的所有数据。而是尝试这样的事情,虽然你并不真的需要一个对象来停止索引和 src
——一个普通的一维数组就可以了:
$("#submit").click(function() {
var total = 3;
var photos = new Array();
for(var i = 0; i < total; i++)
{
var collection = {
'no' : i,
'photo' : $('#thumbnail'+i+'').children('img').attr('src')
};
photos.push( collection );
}
$.ajax({
type: "POST",
url: "<?php echo base_url()?>create/submit",
data: {collection : photos},
cache: false,
success: function(response)
{
console.log(response);
alert('success');
window.location = '<?php echo base_url()?>create/submit';
}
});
});
您发送的数据采用以下形式:
photos = [
{
"no": 1,
"photo":"this is a link"
},
{
"no": 2,
"photo":"this is a link"
},
{
"no": 3,
"photo":"this is a link"
}
]
关于javascript - 从 Ajax 将数组数组传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31152719/