【问题标题】:how make ajax-request through coffee script?如何通过咖啡脚本制作ajax请求?
【发布时间】:2015-10-16 19:22:24
【问题描述】:

请帮忙解决问题。

相册控制器:

  def create
    @album = current_user.albums.build(album_params)

    if @album.save
      flash[:success] = :album_saved
      redirect_to user_album_path(@current_user, @album)
    else
      flash.now[:error] = :album_not_saved
      render 'new'
    end
  end

html表单:

<%= form_for [current_user, @album], remote: true do |f| %>
    <%= f.text_field :title %>
    <%= f.submit %>
<% end %>

布局/_head.html.erb:

<title>Vd</title>
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>

形成它的工作原理。 ajax-request 在数据库中创建一条新记录。

我想在表单中添加一条消息。为此,我添加以下代码

assets/javascript/albums.coffee:

$(document).ready ->
  $("#new_album").on("ajax:success", (e, data, status, xhr) ->
    $("#new_album").append xhr.'<p>album add successfull</p>'
   ).on "ajax:error", (e, xhr, status, error) ->
    $("#new_album").append "<p>ERROR</p>"

因此,表单被加载到屏幕显示以下错误消息:

专辑中的 ExecJS::RuntimeError#new 显示 /home/kalinin/rails/phs/app/views/layouts/_head.html.erb 其中第 3 行 引发:语法错误:[stdin]:8:32:意外字符串 &lt;%= javascript_include_tag 'application', 'data-turbolinks-track' =&gt; true %&gt;

【问题讨论】:

  • 尝试将此行 $("#new_album").append xhr.'&lt;p&gt;album add successfull&lt;/p&gt;' 更改为 $("#new_album").append xhr.responseText
  • 也尝试安装 gem 'therubyracer'
  • responseText 解决了问题

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

我对@9​​87654322@不太了解,但是在查看Guides时,它具有以下代码sn-p

$(document).ready ->
  $("#new_article").on("ajax:success", (e, data, status, xhr) ->
    $("#new_article").append xhr.responseText
  ).on "ajax:error", (e, xhr, status, error) ->
    $("#new_article").append "<p>ERROR</p>"

所以将$("#new_album").append xhr.'&lt;p&gt;album add successfull&lt;/p&gt;' 更改为$("#new_album").append xhr.responseText 应该可以解决您的问题。

【讨论】: