[英]Rails: How do I call 'create' action in jQuery ( .js.erb )?
I am using Rails 4.1.1 I was wondering, how do I call the 'create' action in jQuery ( .js.erb )? 我正在使用Rails 4.1.1,我想知道如何在jQuery(.js.erb)中调用'create'操作? Please see below my jquery codes and my user_controller.rb , I would like to call the user_controller.rb create action in the jquery if else code. 请在下面查看我的jquery代码和我的user_controller.rb , 如果其他代码,我想在jquery中调用user_controller.rb create动作。
routes.rb routes.rb
Rails.application.routes.draw do
resources :user
root 'user#index'
end
user_controller.rb user_controller.rb
class UserController < ApplicationController
def index
@users = User.all
@user = User.new
end
def create
@user = User.new(user_params)
@user.save
redirect_to "/"
end
private
def user_params
params.require(:user).permit(:email)
end
end
subscribe.js.erb subscription.js.erb
$(function () {
$("#subscribe").submit(function (event) {
var input = $('.my-subscribe-message');
if(!input.is(':empty')) {
$('.my-subscribe-message').stop(true);
}
event.preventDefault();
event.stopImmediatePropagation();
var email = $("input#subscribe-email").val();
if (email == "") {
$(".my-subscribe-message").stop(true).html('<i class="fa fa-warning"></i> You must enter a valid e-mail address.');
$("input#subscribe-email").focus();
}
else if (!isValidEmailAddress( email )) {
$(".my-subscribe-message").stop(true).html('<i class="fa fa-warning"></i> E-mail address is not valid.');
$("input#subscribe-email").focus();
}
else {
$.ajax({
/* I would like to call the create action here */
success: function () {
$(".my-subscribe-message").html('<i class="fa fa-check"></i> We will be in touch soon!');
$('input#subscribe-email').val('');
}
});
}
});
});
Give this a punt: 给这个平底锅:
$.ajax({
type: "POST",
url: "/users",
data: { user: { email: "blah@blah.com" } },
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.