I have toggle button on my form and on toggling it i am sending ajax call request to save updated boolean value in the database from controller. but it is sending Html and json request both. I just want to send only one json request. (using rails 3.*)
我在我的表单上切换按钮并切换它我发送ajax调用请求以从控制器保存数据库中更新的布尔值。但它发送Html和json请求。我只想发送一个json请求。 (使用导轨3. *)
post_as_premium.html.erb
post_as_premium.html.erb
<%= form_for @editor, url: set_as_premium_reporter_path, remote: true do |f| %>
<div class="editorSettings">
<div class="premiumCheck">
<label class="clearfix" for="user_post_premium_permission">
<span class="checkBoxWrap <%= @editor.post_premium_permission ? 'allChecked' : '' %>">
<%= f.check_box :post_premium_permission %>
</span>
</label>
</div>
</div>
<% end %>
<script type="text/javascript">
if($("#user_post_premium_permission").parent("span").hasClass('allChecked')){
$("#user_post_premium_permission").attr('checked', true);
}else{
$("#user_post_premium_permission").attr('checked', false);
}
$("#user_post_premium_permission").on("change", function(){
if ($(this).prop('checked')){
$(this).parent("span").addClass("allChecked");
}else{
$(this).parent("span").removeClass("allChecked");
}
this.form.submit();
});
</script>
2 ] Controller -
2]控制器 -
def post_as_premium
@editor = current_user
end
def set_as_premium
if params[:editor] && params[:user][:post_premium_permission]
current_user.update_attributes(post_premium_permission: params[:user][:post_premium_permission])
respond_to do |format|
format.js { head :ok }
format.html { redirect_to post_as_premium_path(current_user)}
end
end
1 个解决方案
#1
1
Instead of submitting the form with form.submit()
you could make an AJAX POST request with $.post
您可以使用$ .post进行AJAX POST请求,而不是使用form.submit()提交表单
$("#user_post_premium_permission").on("change", function(){
if ($(this).prop('checked')){
$(this).parent("span").addClass("allChecked");
} else {
$(this).parent("span").removeClass("allChecked");
}
// AJAX POST request
var url = $(this).parent("form").attr('action')
$.post(url, { editor: { post_premium_permission: $(this).prop('checked') } })
});
#1
1
Instead of submitting the form with form.submit()
you could make an AJAX POST request with $.post
您可以使用$ .post进行AJAX POST请求,而不是使用form.submit()提交表单
$("#user_post_premium_permission").on("change", function(){
if ($(this).prop('checked')){
$(this).parent("span").addClass("allChecked");
} else {
$(this).parent("span").removeClass("allChecked");
}
// AJAX POST request
var url = $(this).parent("form").attr('action')
$.post(url, { editor: { post_premium_permission: $(this).prop('checked') } })
});