[英]Rails: How do load/trigger a js.erb using the controller?
I'm not even sure how to ask this question in a way thats understandable. 我什至不知道如何以一种可以理解的方式问这个问题。
Basically, I'd like to do some javascript using a js.erb after I save. 基本上,我想在保存后使用js.erb做一些JavaScript。 I'm submitting the form using a regular javascript/coffee-script file (if all fields are filled in correctly, then the form is submitted, else the form does nothing & just displays errors). 我使用常规的javascript / coffee-script文件提交表单(如果正确填写了所有字段,则提交表单,否则表单不执行任何操作并仅显示错误)。
Part of my coffee-script: 我的咖啡脚本的一部分:
fieldCorrectResponse: (fields, response) ->
if fields == correct
$('#new_mail')[0].submit()
else
$('#mail_error').text('error while filling out form')
my mail controller: 我的邮件控制器:
def create
@mail = Mail.new(mail_params)
if @mail.save
#PERFORM SOME JS USING A JS.ERB
else
render :new
end
END
So I guess what I'm really is asking is, how would you call a js.erb in the controller? 所以我想我真正要问的是,您将如何在控制器中调用js.erb?
Wrote the solution to my problem below.. 在下面为我的问题写了解决方案。
You should be able to render js
and use create.js.erb
. 您应该能够呈现js
并使用create.js.erb
。
Please try: 请试试:
# MailsController
def create
@mail = Mail.new(mail_params)
if @mail.save
respond_to do |format|
format.js
end
else
render :new
end
END
Then, implement your javascript in app/views/mails/create.js.erb
. 然后,在app/views/mails/create.js.erb
实现您的javascript。
"do some javascript" isn't terribly descriptive. “做一些javascript”并不是非常描述性的。 are you wanting to return a JSON object from the create action, which can then be parsed by the success callback on your jquery? 您是否要从create操作返回一个JSON对象,然后可以通过jquery上的成功回调对其进行解析? Or do you want to have a template that has javascript in it that gets called as a result of the save action? 还是您想要一个包含javascript的模板,该模板是通过save操作调用的?
vinod covered the second way. vinod涵盖了第二种方式。 make sure you have your routes set up correctly. 确保您的路线设置正确。
if you want to return a parseable JSON object, then write 如果您想返回一个可解析的JSON对象,请编写
render json: { some: 'json objects', should: 'go here' }
Also, not knowing what "mails" are, if you're trying to send emails that should be done with action mailer, and probably done as a part of committing the main model to the database (if you're creating a user and also trying to send an email, have a method as part of user creation that sends out the email). 另外,如果您要发送的邮件应该使用动作邮件程序完成,并且不知道是什么“邮件”,那么这可能是将主要模型提交到数据库的一部分(如果您要创建用户,尝试发送电子邮件,请在用户创建过程中使用一种方法来发送电子邮件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.