我正在使用远程表单在 Rails 中提交评论。不应将用户发送到新页面,因为我正在使用此远程表单。
当我点击“提交”时,我希望它有一个淡入淡出的状态,上面写着“感谢提交”并且表格清晰。然而,我无法弄清楚如何为我的生活做到这一点。
问题在于,当我执行 $('form').submit -> 然后清除文本区域时,它会在我实际完成提交之前将其重置,所以我在 Rails 中得到一个空白提交。
我正在使用 Rails 3.2、Coffeescript 和 Jquery。
我正在使用远程表单在 Rails 中提交评论。不应将用户发送到新页面,因为我正在使用此远程表单。
当我点击“提交”时,我希望它有一个淡入淡出的状态,上面写着“感谢提交”并且表格清晰。然而,我无法弄清楚如何为我的生活做到这一点。
问题在于,当我执行 $('form').submit -> 然后清除文本区域时,它会在我实际完成提交之前将其重置,所以我在 Rails 中得到一个空白提交。
我正在使用 Rails 3.2、Coffeescript 和 Jquery。
也许您希望在提交表单时执行此操作,但是……您使用 jQuery 的绑定(或实时)方法并等待它返回成功。
$('#submit_button')
.live('ajax:success', clearForm)
.live('ajax:success', notifyUser)
如果你想不管成功还是在请求的任何阶段都这样做,请检查其他可用的 ajax 回调“beforeSend”、“完成”、“错误”等。
DanS 答案的变体:
$('form').submit (e) ->
e.preventDefault() # prevent form submitting multiple times
$.post(@action, $(@).serializeArray()).done -> # manually submit the form
$(@).find('input').each -> @reset() # afterwards clear the form
return
我在 ajax 调用之后添加了 done 回调,这将强制在清除表单之前等待 ajax 完成。
这应该有效:
$('form').submit (e) ->
e.preventDefault() # prevent form submitting multiple times
$.post @action, $(@).serializeArray() # manually submit the form
$(@).find('input').each -> @reset() # afterwards clear the form
return
它产生以下javascript:
$('form').submit(function(e) {
e.preventDefault();
$.post(this.action, $(this).serializeArray());
$(this).find('input').each(function() {
return this.reset();
});
});
表单提交将加载一个新页面。如果您想让用户保持在同一页面上并仍然提交表单数据,您必须手动发送表单:
$('form').bind 'submit', (e) ->
e.preventDefault() # don't send the user to a new page
$.post this.action, $(this).serializeArray() # manually submit formdata to form url
$(this).find(':input').each -> this.reset() # reset all fields in the form
(以上我没有测试,希望没有错误)