在 rails 5 中的 coffeescript 中渲染 ajax:success 上的部分内容

render a partial on ajax:success in coffeescript in rails 5

我正在尝试使用咖啡脚本 ajax 调用后渲染部分内容,但无法完成。

根据 AJAX 请求调用的控制器

 def unfollow
     @user = User.find(params[:follow][:followed_id])
     current_user.unfollow!(@user)
     render json: {result: "success"}
 end

部分:User/follow.html.erb

 <div id="follow_button">
   <%=form_for(:follow,url: follow_users_path,remote:true) do |f| %>
     <%= f.hidden_field :followed_id, value: @user.id %>
     <%= f.submit "Follow", id: "Follow_button", class: "btn btn-primary" %>
   <% end %>
 </div>

Ajax:成功函数

 $ ->
     $('#unfollow_button').on "ajax:success", (e,data,status,xhr)  ->
     $('#follow_unfollow_button').html("<%= escape_javascript( render partial: 'users/follow') %>")

HTML 在那个地方

 <div id="unfollow_button">
      <%=form_for(:follow,url: unfollow_users_path,remote:true) do |f| %>
      <%= f.hidden_field :followed_id, value: @user.id %>
      <%= f.submit "Unfollow", id: "unfollow_button", class: "btn btn-primary" %>
      <% end %>
 </div>

我没有从服务器获取任何值我只想在 ajax 成功时呈现它。但它呈现这样

    <%= escape_javascript( render partial: 'users/follow') %>

如何解决这个问题?我错过了什么?

是的,您不能从 json 那样的响应中在 javascript 内呈现 erb 部分。修复方法如下

1) 从控制器中删除这一行

render json: {result: "success"}

2) 在 views/users/ 中使用以下代码创建一个名为 unfollow.js.coffee 的文件

$('#follow_unfollow_button').html("<%= j render('users/follow') %>")

3) 您不再需要绑定到 ajax success 函数,因此请从您拥有的任何地方完全删除此代码

 $ ->
     $('#unfollow_button').on "ajax:success", (e,data,status,xhr)  ->
     $('#follow_unfollow_button').html("<%= escape_javascript( render partial: 'users/follow') %>")

在这种情况下,不要尝试从 coffeescript 渲染它。相反,将来自控制器和 return 的结果作为数据呈现给 ajax。

1) 将控制器方法更改为

def unfollow
     @user = User.find(params[:follow][:followed_id])
     current_user.unfollow!(@user)
     render 'users/follow', :layout => false
 end

2) 将JS函数改成

$ ->
     $('#unfollow_button').on "ajax:success", (e,data,status,xhr)  ->
     $('#follow_unfollow_button').html(data)

由于您的控制器将 return 某些东西(而不是错误),ajax:success 将启动,而不是尝试在 JS/coffeescript 中渲染它,只需在控制器中渲染它这样一来,您也不需要仅仅为了 return 向客户发送信息而呈现某些内容。