ajax请求后控制器处理

时间:2018-12-26 05:43:20

标签: javascript ruby-on-rails ruby ajax post

我试图使一个简单的ajax发布请求正常工作,以便当我单击html页面上的按钮时,将调用javascript事件侦听器,从而发出ajax发布请求,并返回一些文本。我正在尝试使其正常工作,以便ajax请求中的成功函数可以打印出接收到的文本,但是在完成此操作时遇到了麻烦,并认为这是因为controller.rb文件如何处理请求。到目前为止,我有:

index.html.erb

<%= javascript_include_tag "application" %>

<h1>Welcome to my website#index</h1>

<input class="className" id="idName" type="button" value="Click Me!" id="my_button" remote:true/>

<ul id="ulID">
 <div class = 'wantToChange'>This should change when button is pressd.</div>
</ul>

application.js

$(document).ready(function(){
    $('.className').on('click', function(){
        console.log("inside js click listener");

       $.post('superman', { field1: "hello", field2 : "hello2"}, 
       function(returnedData){
            console.log(returnedData);
       });

    });
});

welcome_controller.rb

class WelcomeController < ApplicationController
  def index
  end

  def superman
    some_parameter = params[:some_parameter]
    #do something with some_parameter and return the results
    render plain: "OK"
  end

end

routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

  resources :test do
    collection do
      get 'test'
    end
  end

  root 'welcome#index'
end

但是,当我单击按钮时,运行它只会产生以下错误:     POST http://localhost:3000/superman 404(未找到) 这使我认为我的控制器文件未正确设置以接收此“超人”路线?非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:0)

1 => Index.html.erb

<!-- this line should be in application.html.erb 
  <%#= javascript_include_tag "application" %>
-->
<h1>Welcome to my website#index</h1>

<input class="className" id="button_to_be_clicked" type="button" value="Click Me!" id="my_button"/>

<ul id="ulID">
 <div class = 'want_to_change'>This should change when button is pressd.</div>
</ul>

   <script type="text/javascript">
     $('#button_to_be_clicked').on('click', function(){
      // ajax request 
       $.ajax({
         url: "/superman",
         type: "POST",
         data : {
           value1: "hello",
           value2: "hello2"            
         },
         dataType: "script",
      });        
     })
   </script>

2 => route.rb

Rails.application.routes.draw do
  root 'welcome#index'

  post '/superman', to: 'welcome#superman'

  resources :test do
    collection do
      get 'test'
    end
  end
end

3 => welcome_controller.rb

class WelcomeController < ApplicationController
  def index
  end

  def superman
    value1 = params[:value1]
    value1 = params[:value2]
    render plain: "OK"
  end

end

3 => superman.js.erb

$('.want_to_change').html("Text to be changed on ajax request.")

答案 1 :(得分:0)

您可以使用 remotipart 宝石执行ajax请求。 您只需添加宝石

gem 'remotipart', github: 'mshibuya/remotipart', ref: '88d9a7'

然后您需要对表单进行一些简单的更改

<%= form_for @document, :html => { :multipart => true, :id => "create-document-form" }, :remote => true do |document_form| %>
  <%= document_form.file_field :file_upload, class: "custom-file-input" %>
<% end %>

例如,我正在使用以上表格通过throgh ajax发布新文档 所以在控制器中它将直接出现

def create
  @document = Document.new(document_params)
  respond_to do |format|
    if @document.save
      data = {visible_for_client: @document.visible_for_client, file_name: file_name.to_json, description: @document.description, file_path: file_url}.to_json
      format.js { render :js => "append_document(#{data});" }
    else
      format.json { render json: { errors: @document.errors.full_messages }, status: 422 }
    end
  end
end

所以我会从控制器中调用js方法,并将消息数据和消息传递给该方法。

function append_document(data){
  console.log("Document created successfully.")
}