Rails通过Ajax提交表单

时间:2018-06-27 16:51:29

标签: javascript ruby-on-rails ajax

在Rails中使用Ajax存在一些问题。我想在我的Wellcome / inex页面上创建新帖子。但是当我按一下botton时会显示

没有路由与[POST]“ / welcome / index”

匹配

wellcome / index.html

    <b>Projects</b>

    <ul id="projects">
    <% @projects.each do |project| %>
      <h2><%= project.title %></h2>
    <% end %>
    </ul>

    <br>

    <%= form_for :project do |f| %>
    <%= f.text_field :title, :placeholder => ' Enter new project here..' %>
    <but><%= f.submit 'Add Project'%></but>
    <% end %>

welcome_controller.rb

class WelcomeController < ApplicationController
  def index
      @projects = Project.all
      @project = Project.new
  end

def create
  @project = Project.new(project_params)

  respond_to do |format|
    if @project.save
      format.html { redirect_to @project, notice: 'project was successfully created.' }
      format.js  
      format.json { render json: @project, status: :created, location: @project }
    else
      format.html { render action: "new" }
      format.json { render json: @project.errors, status: :unprocessable_entity }
    end
  end
end

    private
  def project_params
    params.require(:project).permit(:title)
  end


end

create.js.erb

$('#projects').html("<%= escape_javascript (render 'projects') %>");

路线项目

Prefix Verb   URI Pattern                 Controller#Action
project_index GET    /project(.:format)          project#index
              POST   /project(.:format)          project#create
  new_project GET    /project/new(.:format)      project#new
 edit_project GET    /project/:id/edit(.:format) project#edit
      project GET    /project/:id(.:format)      project#show
              PATCH  /project/:id(.:format)      project#update
              PUT    /project/:id(.:format)      project#update
              DELETE /project/:id(.:format)      project#destroy

花了很多时间使用AJAX进行更新,但每次都失败。有什么需要帮助的吗?预先感谢

2 个答案:

答案 0 :(得分:0)

您必须将remote: true添加到表单中。

<%= form_for @project, url: project_index_path, remote: true do |f| %>
    <%= f.text_field :title, :placeholder => ' Enter new project here..' %>
    <but><%= f.submit 'Add Project'%></but>
<% end %>

答案 1 :(得分:0)

如果要集成Ajax和Ruby,则需要在链接操作内添加以下行

remote:true

您还可以检查有关Ajax和Ruby的信息 How Ajax works with ruby on rails