2017-09-16 76 views
1

到mysql我送一個JSON數組我的控制器將其保存到數據庫中,JSON數組看起來像這樣節能陣列使用JQuery AJAX

var events = [{ 
"title": "English Lesson Schedule", 
"start": "2017-09-17 06:30 AM", 
"end": "2017-09-17 09:00 AM", 
"date": "2017-09-17", 
"student": "1", 
"teacher": "2", 
"id": 1 
}, { 
"title": "English Lesson Schedule", 
"start": "2017-09-18 09:00 AM", 
"end": "2017-09-18 10:30 AM", 
"date": "2017-09-18", 
"student": "1", 
"teacher": "2", 
"id": 2 
}] 

這裏是我如何通過JQuery AJAX發送它

$.ajax({ 
    type: "POST", 
    url: pp_return_url, 
    data: { 
     _token:token, 
     "eventsArray": JSON.stringify(events)     
    }, 
    success: function(response) { 
     console.log(response) 
    } 
}); 

,這裏是我如何處理它在我的控制器上

public function payPalTest(Request $request){ 
    $events = json_decode($request['eventsArray']); 

     foreach ($events as $key => $event) { 
      $sched[$key] = new Schedule(); 
      $sched[$key]->student = $event[$key]['student']; 
      $sched[$key]->teacher = $event[$key]['teacher']; 
      $sched[$key]->lesson_name = $event[$key]['title']; 
      $sched[$key]->lesson_date = $event[$key]['date']; 
      $sched[$key]->time_start = $event[$key]['start']; 
      $sched[$key]->time_end = $event[$key]['end']; 
      $sched[$key]->save(); 
     } 
     return response('SUCCESS'); 
} 

我的問題是,我得到一個Invalid argument supplied for foreach()來自我的控制器的錯誤響應。任何想法我在這裏做錯了什麼?謝謝

+0

做一個JSON.stringify轉換的JSON字符串..直接傳遞JSON,看看你是否得到的數據在PHP –

回答

0

好吧,我發現我的錯誤已經。

我沒注意,我試圖從陣列內的單個對象獲得的值,從而代替

foreach ($events as $key => $event) { 
     $sched[$key] = new Schedule(); 
     $sched[$key]->student = $event[$key]['student']; 
     $sched[$key]->teacher = $event[$key]['teacher']; 
     $sched[$key]->lesson_name = $event[$key]['title']; 
     $sched[$key]->lesson_date = $event[$key]['date']; 
     $sched[$key]->time_start = $event[$key]['start']; 
     $sched[$key]->time_end = $event[$key]['end']; 
     $sched[$key]->save(); 
    } 

我通過改變可變$event$events因爲$events固定它是收集和我我通過它的循環,所以我做了這個

foreach ($events as $key => $event) { 
     $sched[$key] = new Schedule(); 
     $sched[$key]->student = $events[$key]['student']; 
     $sched[$key]->teacher = $events[$key]['teacher']; 
     $sched[$key]->lesson_name = $events[$key]['title']; 
     $sched[$key]->lesson_date = $events[$key]['date']; 
     $sched[$key]->time_start = $events[$key]['start']; 
     $sched[$key]->time_end = $events[$key]['end']; 
     $sched[$key]->save(); 
    } 

通過索引獲取值現在,它的工作,我可以將它保存在我的數據庫