简体   繁体   English

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

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

I am building an ActiveAdmin form as part of a project that started as a simple html+jquery form. 我正在将ActiveAdmin表单构建为作为简单html + jquery表单开始的项目的一部分。 As a non-rubyist I am struggling to understand this framework and how I would create a form that sends data to an external server. 作为一名非鲁本主义者,我正在努力了解此框架以及如何创建将数据发送到外部服务器的表单。 So far I have this: 到目前为止,我有这个:

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

However, while this does send the post request, it also navigates to this endpoint. 但是,尽管这确实发送了发布请求,但它也导航到该端点。 I am looking for a form that simply sends data when the form is submitted. 我正在寻找一种仅在提交表单时发送数据的表单。

How can I do this? 我怎样才能做到这一点?

You need to set set remote: true to your form builder for ajax: 您需要为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

In you controller you need a respond_to block which in normal rails cases you would be handling some data, and return something for the browser as json data, normally the model, but since in your example there's not model, just some text that we don't know what you want to do with, you can just respond with either json or javascript. 在您的控制器中,您需要一个respond_to块,在正常情况下,您将处理一些数据,并以json数据(通常为模型)的形式返回浏览器某些内容,但是由于在您的示例中没有模型,因此我们仅提供一些文本不知道您想做什么,您可以使用json或javascript进行响应。

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

You probably should read the documentation which shows how to do AJAX on rails 您可能应该阅读说明如何在导轨上进行AJAX的文档

How is your controller/route responding to the action? 您的控制器/路由如何响应操作? Maybe the handler is making the redirect. 也许处理程序正在进行重定向。 Try to respond with a simple alert and see what happens. 尝试以简单的警报响应,然后看看会发生什么。

With that, watch for the network request too and the response, to see what status code is being returned. 这样一来,还要注意网络请求和响应,以查看返回了什么状态代码。

cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM