我有一个使用 Webpacker、jQuery 3 的 Rails 5.1 应用程序。在发出 Ajax 帖子后,我尝试将 json 渲染回浏览器。这是我的 Controller :
def create
@giver = Giver.new(giver_params)
return unless @giver.valid?
if @giver.save
render json: { location: 'url' }, status: :ok
end
end
这是我的 javascript(我有一条将/give 定向到 Controller 的创建方法的路由):
$form.get(0).submit();
var jqxhr = $.ajax({
url: '/give',
type: 'POST',
dataType: 'json',
data: $form.serialize()
})
.done(function() {
console.log(jqxhr['responseText']);
$('#new-gift').hide(function() {
$('#confirm-gift').show();
});
return false;
})
.fail(function() {
})
.always(function() {
});
}
我已经这样做了很多次,没有任何问题,但由于某种原因它现在正在渲染
{"location":"url"}
在屏幕上,不执行 .done
调用中的任何功能(隐藏/显示 div)。它也可以将所有内容保存到数据库中。我认为 .done
部分中的 return false;
可以解决问题,但事实并非如此。有任何想法吗?我看不到任何其他问题可以解决这个问题 - 如果有,请指导我找到答案。谢谢。
.container.active-div#new-gift
= form_for @giver, url: give_path, remote: true, html: { id: "payment-form" } do |f|
%h3 Your Information
.panel-body
.row
.col-md-6
= f.text_field :first_name, class: "form-control", placeholder: "First Name"
%br/
.col-md-6
= f.text_field :last_name, class: "form-control", placeholder: "Last Name"
%br/
.row
.col-md-12.text-center
%br/
= button_tag "Donate", class: "btn btn-primary btn-lg submit", style: "width: 150px; margin-bottom: 50px;"
最佳答案
由于您正在触发手动 ajax
表单提交,因此表单中不需要 remote: true
。只需从表单中删除 remote: true
并阻止表单提交事件触发即可。然后,代码将如下所示
$("#payment-form").submit(function(event){
var jqxhr = $.ajax({
url: '/give',
type: 'POST',
dataType: 'json',
data: $form.serialize()
})
.done(function() {
console.log(jqxhr['responseText']);
$('#new-gift').hide(function() {
$('#confirm-gift').show();
});
});
.fail(function() {
})
.always(function() {
});
event.preventDefault();
});
希望这会有所帮助。
关于javascript - Rails 渲染 json 显示在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48170276/