使用Ajax将JSON对象发布到php

时间:2017-01-21 01:21:16

标签: php jquery json ajax codeigniter

我通过从下拉列表中选择选项来动态添加表行,然后我尝试使用ajax作为json格式的数组将html表行发送到php函数。但是,当我提交多行时,php函数不会打印控制台日志中的所有行。我得到了一次或两次所需的输出。我想我在php函数中遗漏了一些东西。请检查一次。如果需要有关代码的更多信息,请告诉我,我会更新。

使用Javascript:

function storeClgValues() {
  var CollegeData= new Array();
  $('#collegetable tr').each(function(row, tr){
    CollegeData[row]={
        "college" : $(tr).find('td:eq(0)').text()
    }
  }); 
  CollegeData.shift();
  return CollegeData;

}

$('#submit').click(function() { 

 CollegeData=storeClgValues();
 CollegeData=$.toJSON(CollegeData);                     
 $.ajax({
       type:"POST",
       url: '<?php echo base_url();?>ajaxController/insertcollege',
       data: "CollegeData=" + CollegeData,
       success: function(msg) {
          console.log(CollegeData);
          console.log(msg);             
       }
  });

});

AjaxController类中的PHP函数:

 public function insertcollege()
 {   
    $data=array();
    $data=stripcslashes($_POST['CollegeData']);
    $data=json_decode($data, TRUE);
    //echo $data[0]['college'].'<br>';
    //echo $data[1]['college'].'<br>';
    if (is_array($data) || is_object($data))
    {
        foreach ($data as $key => $item) {
            echo $item['college'].'<br>';
        }
    }
 }

在三次尝试中在控制台中输出:

[{"college":"College of Agriculture"}]
College of Agriculture

[{"college":"College of Agriculture"},{"college":"College of Business"}]
College of Agriculture 
College of Business

[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]
<!--nothing gets printed-->

1 个答案:

答案 0 :(得分:1)

试试这个......

<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
    {
        foreach ($data as $key => $item) {
            $output[]=$item['college'].'<br>';
        }
    }
echo json_encode($output);

?>

OR

<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
    foreach ($data as $key => $item) {
        foreach($item as $value){
            $output[] = $value."</br>";
        }
    }
}   
echo json_encode($output);
?>