2016-02-10 71 views
0

我想這個數組var data_array傳遞到我的控制器通AJAX關聯數組沒有當傳遞給控制器​​通AJAX

此數組是var data_array值當我使用alert(JSON.stringify(data_array));

enter image description here

這是我的AJAX方法

var project_details = $.extend({}, data_array); 

    $.ajax({ 
     type: "POST", 
     url: "<?php echo base_url('PPMP_controller/submitPPMP'); ?>", 
     data: { data_array : $.param(project_details) }, 
     dataType: 'json', 
     success: function(data) { 
      alert('PPMP submission success!'); 
      alert(data); 
     }, 
     error: function(errorw) { 
      console.log(errorw); 
     } 
    });  

這是我PPMP_controller

public function submitPPMP(){ 
    $data_array = $this->input->post('data_array'); 
    $value = $this->PPMP_model->submitPPMP($data_array); 
    echo json_encode($value); 
} 

這是我的模型

function submitPPMP($data_array){ 
    $date_format = 'DATE_W3C'; 

    $date_submitted = standard_date($date_format); 
    $data = array(
     'user_id' => 1, 
     'date_submitted' => $date_submitted, 
     'first_lvl_status' => 0, 
     'second_lvl_status' => 0, 
     'third_lvl_status' => 0, 
     'fourth_lvl_status' => 0, 
     'submitted' => 1 
    ); 
    $this->db->insert('project', $data); 
    $id = $this->db->insert_id(); 

    if(is_array($data_array) || is_object($data_array)){ 
     return "yes"; 
     foreach($data_array as $object){ 
      $project_details = array(
       'project_id' => $id, 
       'supply_id' => $object->supply_id, 
       'supply_description' => $object->supply_description, 
       'quantity' => $object->quantity, 
       'price' => $object->price, 
       'jan' => $object->jan, 
       'feb' => $object->feb, 
       'mar' => $object->mar, 
       'apr' => $object->apr, 
       'may' => $object->may, 
       'jun' => $object->jun, 
       'jul' => $object->jul, 
       'aug' => $object->aug, 
       'sep' => $object->sep, 
       'oct' => $object->oct, 
       'nov' => $object->nov, 
       'dec' => $object->dec 
      ); 
      $this->db->insert('project_details', $project_details); 
     } 
    } 
    else{ 
     return "no"; 
    } 
    return $this->db->last_query(); 
} 

但是從控制器模型傳遞的數組不是一個數組,因爲它不走直通線if(is_array($data_array) || is_object($data_array))而是轉到else條件和return "no"

什麼可能導致此數組不能從控制器傳遞數組到模型。感謝您的幫助。我使用Codeigniter 3.0作爲MVC框架。

回答

0

您傳遞JSON到您的模型不陣列,當涉及到你的模型應該是,

嘗試var_dump($data_array)檢查其數據類型,即jsonobjectarray

$data_array = json_decode($data_array); // to get object  
$data_array = json_decode($data_array,true); // to get array 

PPMP_controller應該是

public function submitPPMP(){ 
    $data_array = $this->input->post('data_array'); 
    $data_array = json_decode($data_array); 
    $value = $this->PPMP_model->submitPPMP($data_array); 
    echo json_encode($value); 
} 
+0

我試着把'$ data_array = json_decode($ data_array);'爲模型a nd控制器,但我的模型仍然'返回「no」' –

+0

嘗試'var_dump($ data_array)'來檢查傳遞給你的模型或控制器的數據類型? – Noman

+0

我應該在哪裏放var_dump($ data_array);'當我在做'$ data_array = json_decode($ data_array)之後放它時''沒有任何反應。也許是因爲AJAX請求? –

相關問題