25

所以我一直在谷歌上搜索如何设置它们,最后我得到了这段代码。

<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>

但它不起作用,我不知道为什么,我确定我做错了什么,我是 RoR 的新手,我喜欢这样一个事实,即我可以声明这个遥控器:它本身的形式是真实的,一旦我弄清楚如何设置回调我会很好去 :) 提前谢谢。

4

5 回答 5

43

根据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>

类似的代码在 Rails 3.2.14 和 jquery-rails 3.0.4 中为我工作

希望能帮助到你。

于 2013-11-20T18:41:50.680 回答
9

由于 Rails 5.1,必须通过 event.detail 提取响应、状态和 xhr 参见: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;
});
于 2019-08-02T08:53:39.077 回答
4

Turbolinks 兼容

<script type="text/javascript">

    $(document).on('ajax:success', 'a[data-remote].watching', function(e, data, status, xhr){

    });

</script>
于 2013-11-26T23:23:10.167 回答
3

试试这个:

把你的javascript代码放在document ready

<script>
$(document).ready(function(){
  $('#reportform')
    .bind("ajax:success", function(data, status, xhr) {
        $('#reportalert').text('Done.');
    });
    .bind("ajax:error", function(xhr, status, error) {

        $('#reportalert').text('Failed.');

    });
})
</script>
于 2013-03-13T20:18:00.183 回答
0

您不必使用 jQuery。能做:

document.querySelector('#reportform')
    .addEventListener("ajax:success", function(data, status, xhr) {
        document.querySelector('#reportform').text('Done.');
    });
    .addEventListener("ajax:error", function(xhr, status, error) {
        document.querySelector('#reportform').text('Failed.');
    });
于 2020-04-14T17:58:18.853 回答