October CMS - API 生成器 - 如何在数据库中创建和更新数据

October CMS - API Generator - how to create and update data in database

我尝试使用 AJAX 和 October CMS 中名为 "API Generator" 的插件将数据发送到数据库。
我无法在其文档或 Google 中找到任何对我有帮助的内容。

我的代码是这样的:

$data = [{'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01', 'departure': '2018-04-03,', 'reservation_type': 'owner'}]

$.ajax({
  url: '/api/v1/booking/create',
  data: $data,
  type: "post"
})
.done(function() {
  console.log('Success')
})
.fail(function() {
  console.warn('Something went wrong');
});

我没有收到任何错误,事实上,我在控制台收到 'Success' 消息,但数据没有添加到数据库中。

我做错了什么? 请帮忙

谢谢。

实际上你做的有点不对 [ 你在 wrong end-point ] 触发 Ajax 请求Api 插件基于 https://laravel.com/docs/5.6/controllers#resource-controllers Resource Controller

So, To create an item you need to fire only POST request to Created Api-End Point. You don't need to send Array just send simple plain Object

重构您的代码(这应该有效):

// Plaing object no array
$data = {'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01',
       'departure': '2018-04-03,', 'reservation_type': 'owner'};

$.ajax({
    url: '/api/v1/booking', // <- just your Api-End [no create/store]
    data: $data,
    type: "post" // <- this post request indicates that you want to create/insert
})
.done(function(response) {
    // this will always fire when status code is 200
    console.log('Success', response); 
})
.fail(function() {
    // when status code is not 200 this will execute
    console.warn('Something went wrong');
});

Why you get success although its not Creating Record ?

因为根据 Resource Controller api generator controller 中没有方法 create 所以 October CMS/api/v1/booking/create [POST] 请求视为404 page not found 及其服务 [200] 状态代码 404 page not found 作为 ajax response.

And 404 page is having 200 status code so it fall in to success category and Ajax thinks it's a successful request and prints success message in console.

如有疑问请评论。