gpt4 book ai didi

php - 使用 JQuery AJAX 将 JSON 数组保存到 mysql

转载 作者:行者123 更新时间:2023-11-30 21:53:15 25 4
gpt4 key购买 nike

我正在向我的 Controller 发送一个 json 数组以将其保存到数据库,json 数组如下所示

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)
}
});

这是我在 Controller 上处理它的方式

 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');
}

我的问题是我从我的 Controller 收到一个 Invalid argument supplied for foreach() 错误响应。任何想法我在这里做错了什么?谢谢

最佳答案

好的,我已经发现了我的错误。

我没有注意到我试图从数组中的单个对象中获取值,所以不是

 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();
}

现在它可以工作了,我可以将它保存在我的数据库中

关于php - 使用 JQuery AJAX 将 JSON 数组保存到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250323/

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