gpt4 book ai didi

php - 无法使用 AJAX 将数组数据从 View 传递到 Controller

转载 作者:行者123 更新时间:2023-12-01 04:35:48 25 4
gpt4 key购买 nike

在 CodeIgniter (PHP) 中使用 AJAX 时,数据(数组的数组)未从 View 传递到 Controller

url 在 $.ajax 中工作。它正在重定向到 Controller 中的方法

view.php( View )

$('#save').click(function(){
var table_data = [];

// use .each to get all data
$('#data_table tr').each(function(row,tr){

// create array again to store data by row
// get only data with value

if ($(tr).find('td:eq(0)').text() == "") {
} else {
var sub = {
'no' : $(tr).find('td:eq(0)').text(),
'firstname' : $(tr).find('td:eq(1)').text(),
'middle' : $(tr).find('td:eq(2)').text(),
'last' : $(tr).find('td:eq(3)').text(),
};

table_data.push(sub);
}
});

//use ajax to insert the data

console.log(table_data);

var data = {'data_table':table_data};

console.log(data);

$.ajax({
data : data,
type : 'POST',
url : 'save',
crossOrigin : false,
dataType : 'array',
success: function(msg){
$('.answer').html(msg);
}

});

Welcome.php( Controller )

public function save() {

$relatives_list = $this->input->post('data');
echo 'as';

echo $relatives_list;
// the list is not shown here

$this->load->model('Batch');
$status = $this->Batch->save($relatives_list);

$this->output->set_content_type('application/json');
echo json_encode(array('status' => $status));
}

Batch.php(模型)

 public function save($relative_list){
$length = count($relative_list);

for($x = 0; $x < count($relative_list); $x++){
$data[] = array(
'no' => $relative_list[$x]['no'],
'firstname' => $relative_list[$x]['firstname'],
'middle' => $relative_list[$x]['middle'],
'last' => $relative_list[$x]['last'],

);
}
try {


for($x = 0; $x<count($relative_list); $x++){
$this->db->insert('hhh',$data[$x]);
}
return 'success';
}catch(Exception $e) {
return 'failed';
}

}

错误:

parameter-must-be-an-array-or-an-object-that-implements-countable

最佳答案

根据您的脚本,它不会是data,而是data_table

var data = {'data_table':table_data};

因此:

var_dump($this->input->post('data_table')

如果这不起作用,请发布您的 data 变量的 console.log

请注意:完成故障排除后,您必须删除 json_encode 之前的 echo,否则 jquery 将无法解析响应。

关于php - 无法使用 AJAX 将数组数据从 View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56290529/

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