ActiveAdmin - 如何通过 AJAX 向表单提交按钮发送 http 请求

ActiveAdmin - How to send an http request to a form submit button via AJAX

我正在构建一个 ActiveAdmin 表单作为项目的一部分,该项目最初是一个简单的 html+jquery 表单。作为一个非 ruby​​ist,我正在努力理解这个框架以及我将如何创建一个将数据发送到外部服务器的表单。到目前为止我有这个:

form action: "http://localhost:3000/test", method :post do |f|
   f.input :my_field, type: text, name: 'test_field'
   f.input :submit, type: :submit
end

但是,虽然这会发送 post 请求,但它也会导航到此端点。我正在寻找一种在提交表单时仅发送数据的表单。

我该怎么做?

您需要为 ajax 的表单生成器设置 set remote: true:

form action: "http://localhost:3000/test", method :post, remote: true do |f|
   f.input :my_field, type: text, name: 'test_field'
   f.input :submit, type: :submit
end

在你的控制器中你需要一个 respond_to 块,在正常的 rails 情况下你会处理一些数据,return 一些浏览器的 json 数据,通常是模型,但由于在您的示例中没有模型,只有一些我们不知道您想要做什么的文本,您可以使用 json 或 javascript.

def test 
  respond_to do |format|
    format.js
    format.json { render json: {text: params[:text]}, status: :success
  end
end

您可能应该阅读 documentation,其中显示了如何在 rails

上执行 AJAX

您的 controller/route 对操作的反应如何?也许处理程序正在进行重定向。尝试用简单的警报响应,看看会发生什么。

这样,还要注意网络请求和响应,以查看返回的状态代码。

干杯