【问题标题】:Rails AJAX form keeps rendering as HTMLRails AJAX 表单一直呈现为 HTML
【发布时间】:2013-02-03 14:25:39
【问题描述】:

我正在尝试向基本表单添加一些 ajax,尽管它一直呈现为 html

OpponentsController#create as HTML 处理

我的看法

<%= form_for(@opponent, :remote => true, :url => { :controller => "opponents", :action => "create" }) do |f| %>
  <% if @opponent.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@opponent.errors.count, "error") %> prohibited this opponent from being saved:</h2>

      <ul>
      <% @opponent.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

控制器

# POST /opponents
  # POST /opponents.json
  def create
    @opponent = Opponent.new(params[:opponent])

    respond_to do |format|
      if @opponent.save
        format.html { redirect_to(opponents_url,
                                  :notice => "#{@opponent.name}  was successfully created.") }
        format.js { render }
      else
        format.html { render :action => "new" }
        format.json { render :json => @opponent.errors, :status => :unprocessable_entity }
      end
    end
  end

create.js.erb

alert('Hello Rails');

enter code here

【问题讨论】:

  • 您不需要在 form_for 中指定 URL,应该通过调用 form_for @opponent 来处理。还要检查表单 HTML 并确保它实际上设置了 data-remote="true"
  • 看起来数据远程正在设置`
    `
  • 请求是作为 JS 还是 HTML 进入 Rails 的?你确定你的浏览器启用了 JavaScript 吗?
  • 我怎么知道它是以 JS 还是 HTML 的形式出现的,是的,我的浏览器上启用了 javascript
  • 我认为你需要 jquery_ujs。哪个版本的 Rails?

标签: ruby-on-rails jquery ujs


【解决方案1】:

AJAX 表单要求您加载 jquery 和 jquery_ujs。确保将它们包含在应用程序布局标题或 application.js 文件中,如下所示:

# application.js
//= require jquery
//= require jquery_ujs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    相关资源
    最近更新 更多