Dat*_*sik 21 ajax jquery ruby-on-rails ruby-on-rails-3
所以我一直在谷歌搜索如何设置它们,我最终得到了这个代码.
<script>
$('#reportform')
.bind("ajax:success", function(data, status, xhr) {
$('#reportalert').text('Done.');
});
.bind("ajax:error", function(xhr, status, error) {
$('#reportalert').text('Failed.');
});
</script>
<h2>Review Driver</h2>
<p>Fill out your review of the driver</p>
<div class="hero-unit form-signin" id="reportformdiv">
<%= form_for(@report, html: { id: "reportform" }, remote: true, update:
{ success: "response", failure: "error"} ) do |t| %>
<p id="reportalert"></p>
<%= t.text_field :plant_site, placeholder: "Plant Site" %>
<%= t.text_field :route_number, placeholder: "Route Number" %>
<%= t.text_field :driver_name, placeholder: "Driver name if available" %>
<%= t.date_select :date_recorded, html: { class: "input-block-level" } %>
<%= t.text_field :action, placeholder: "Action taken" %>
<%= t.text_area :report_body, placeholder: "What you witnessed",
style: "height: 300px;",
class: "input-block-level" %>
<%= t.submit "File Report", class: "btn btn-primary btn-large" %>
<% end %>
</div>
Run Code Online (Sandbox Code Playgroud)
但它不起作用,我不知道为什么,我确定我做错了什么,我是RoR的新手,我喜欢这样一个事实:我可以声明这个遥远:真实的形式是它的自我,一旦我弄清楚如何设置回调我会很高兴:)提前感谢.
小智 41
根据Rails的wiki,下面的代码应该工作:
<script>
$(document).ready(function(){
$('#reportform').on('ajax:success', function(e, data, status, xhr){
$('#reportalert').text('Done.');
}).on('ajax:error',function(e, xhr, status, error){
$('#reportalert').text('Failed.');
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
在Rails 3.2.14和jquery-rails 3.0.4中,类似的代码对我有用
希望能帮助到你.
由于 Rails 5.1,响应、状态和 xhr 必须通过 event.detail 提取,请参阅:https ://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers
这是一种可能的解决方案:
$(document).on('ajax:success', '#reportform', event => {
const [response, status, xhr] = event.detail;
});
Run Code Online (Sandbox Code Playgroud)