3 回答

TA贡献1839条经验 获得超15个赞
你想要:
停止提交的正常行为。
通过ajax将其发送到服务器。
收到回复并相应地进行更改。
下面的代码应该这样做:
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});

TA贡献1846条经验 获得超7个赞
如果您:remote => true在表单上使用,则可以使用JavaScript通过以下方式提交它们:
$('form#myForm').trigger('submit.rails');

TA贡献1797条经验 获得超6个赞
在Rails 3中进行Ajax表单提交的首选方法是利用Rails-ujs。
基本上,您允许Rails-ujs为您完成ajax提交(并且您无需编写任何js代码)。然后,您只需编写js代码以捕获响应事件(或其他事件)并执行您的操作即可。
这是一些代码:
首先,在form_for中使用remote选项,因此默认情况下,表单将通过ajax提交:
form_for :users, remote:true do |f|
然后,当您要基于ajax响应状态(例如,成功响应)执行某些操作时,请编写如下的javscript逻辑:
$('#your_form').on('ajax:success', function(event, data, status, xhr) {
// Do your thing, data will be the response
});
有几个事件,你可以钩住。
- 3 回答
- 0 关注
- 470 浏览
添加回答
举报