简体   繁体   English

Rails Ajax create.js.erb如何重装部分?

[英]Rails Ajax create.js.erb how to reload partial?

I have a form successfully submitting data via ajax, but I can't figure out how to trigger an event after the ajax action. 我有一个通过ajax成功提交数据的表单,但是我不知道在ajax操作之后如何触发事件。 I'd like to reload the partial containing the form after a new record is submitted. 提交新记录后,我想重新加载包含表单的部分内容。

View 视图

#container
  #partial
   <%= form_for [@qa, @newpdd], :remote => true do |f| %>
    ....
   <%= f.submit "add %>

PDD Controller PDD控制器

def create
@pdd = Pdd.create!(params[:pdd])
@pdd.qa_id = params[:qa_id]
@qa = Qa.find(params[:qa_id])

respond_to do |format|
  if @pdd.save
    format.html { redirect_to(@qa, :notice => 'Pdd was successfully created.') }
    format.xml  { render :xml => @pdd, :status => :created, :location => @pdd }
    format.js
#    render :partial => pddsection
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @pdd.errors, :status => :unprocessable_entity }
  end
end
end

create.js.erb create.js.erb

$('#partial').replaceWith("<%= escape_javascript(render :partial => 'pdds/partial') %>");

Any ideas? 有任何想法吗?

I use the <%=j %> tag instead of <%= escape_javascript() %> , though they may be functionally similar. 我使用<%=j %>标记代替了<%= escape_javascript() %> ,尽管它们在功能上可能相似。

Your code looks good. 您的代码看起来不错。 :remote => true should cause your browser to execute whatever javascript is returned by the server (in this case, create.js.erb). :remote => true应该使您的浏览器执行服务器返回的任何javascript(在这种情况下,为create.js.erb)。 As a troubleshooting step, open up the developer console of your browser and look at the response you are getting from the ajax form submission. 作为故障排除步骤,请打开浏览器的开发人员控制台,然后查看您从ajax表单提交中获得的响应。 Is the correct view rendering? 是正确的视图渲染吗? Is the javascript that ERB rendered correct? ERB呈现的JavaScript是否正确?

If it looks good, copy and paste it in the javascript console. 如果看起来不错,请将其复制并粘贴到javascript控制台中。 If that doesn't update the page, figure out what's wrong with it. 如果那没有更新页面,请找出问题所在。 Could be a bad selector or a syntax error. 可能是错误的选择器或语法错误。

I ended up abandoning the :remote => true condition in the form as demonstrated in this rails cast: 我最终放弃了:remote => true条件,形式如下所示:

Railscast 136 铁轨136

Everything now works as expected. 现在一切正常。 Thanks for the help. 谢谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM