试图弄清楚Ruby on Rails远程:真正的回调

时间:2013-03-13 19:50:48

标签: jquery ruby-on-rails ajax 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>

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

5 个答案:

答案 0 :(得分:40)

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

中,类似的代码对我有用

希望它有所帮助。

答案 1 :(得分: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>

答案 2 :(得分:3)

兼容Turbolinks

<script type="text/javascript">

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

    });

</script>

答案 3 :(得分:3)

自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;
});

答案 4 :(得分:0)

您不必使用jQuery。可以做到:

from transformers import BertForSequenceClassification, AdamW, BertConfig
model_to_parallel = BertForSequenceClassification.from_pretrained(
    "./bert_cache.zip", 
    num_labels = 2, 
    output_attentions = False,
    output_hidden_states = False,
)
model = nn.DataParallel(model_to_parallel,  device_ids=[0,1,2,3]) 
model.to(device)