【问题标题】:October CMS - API Generator - how to create and update data in database十月 CMS - API 生成器 - 如何在数据库中创建和更新数据
【发布时间】:2018-04-26 06:14:35
【问题描述】:

我尝试使用 AJAX 和 10 月 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');
});

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

我做错了什么? 请帮忙。

谢谢。

【问题讨论】:

  • 我不明白你在做什么,帮帮我
  • 我已经使用这个“API Generator”插件为我的预订创建了 API,我尝试将新预订的数据发送到 API 以将其添加到数据库中。 $data 是要添加到数据库的临时静态对象。
  • 找不到解决方案,您必须将服务器端代码发送到连接数据库的位置
  • 我建议您不要使用第三方插件,而是为 API 创建自己的插件,在创建此文件后在 routes.php 内,您可以创建自己的 api 和 php 代码的响应。我按照这种方式。当我使用第三方插件时,我觉得我没有那么多控制权。你可以做这样的事情 - stackoverflow.com/questions/40610006/…。希望这会有所帮助。

标签: ajax api octobercms


【解决方案1】:

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

因此,要创建一个项目,您只需将POST 请求发送到Created Api-End Point。您不需要发送Array 只需发送简单的普通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');
});

为什么你得到success 虽然它不是创建记录?

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

404 页面有 200 个状态码,因此它属于 success 类别和 Ajax thinks it's a successful request 并在控制台中打印 success 消息。

如有任何疑问,请发表评论。

【讨论】:

  • 谢谢您的回答,它确实有帮助:) 但是插件本身还有另一个问题,导致 505 错误。 API 控制器模板中缺少 Validator 类文件导入。
  • 是的,我也看到有些事情没有按预期工作,希望作者尽快纠正它们:)
猜你喜欢
  • 1970-01-01
  • 2017-05-31
  • 2023-04-08
  • 1970-01-01
  • 2019-03-27
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
相关资源
最近更新 更多