未捕获的ReferenceError:未定义数据



我正在使用ajax处理表单提交。属性CCD_ 1的窗体单选按钮。现在,当我尝试alert(data)时,它会提醒[对象对象]

如何提醒当前表单提交。

console.log(数据(

Uncaught ReferenceError: data is not defined

index.html

<script>
$(document).on('turbolinks:load', function() {
$('.<%= attendance_form_id %>').on('ajax:success', function(event){
const [data, status, xhr] = event.detail
$('#<%= attendance_form_id %>').hide()
}).on('ajax:error',function(event){
alert("Something went wrong, please reload page")
});
});
</script>

您真的想在这里重新思考您的整个方法。不使用内联脚本标记(boo(,只需为元素分配一个类,并将脚本移动到资产管道/包中。如果你认为你需要使用ERB插值来定位元素,那你就是做错了。不要认为javascript是特定于单个元素/页面的,只需将其设计为可以通过针对类和/或属性附加到任何元素的行为。

如果您使用ES6功能,这一点尤其重要,因为如果您需要传统浏览器支持,内联脚本标记将不会通过任何转发器传递。

使用委托的事件处理程序:,而不是将代码包装在turbolinks:load事件处理程序(boo(中并将处理程序直接附加到元素

$(document).on('ajax:success', '.my_spiffy_form', function(event){
const $form = $(this); // this is bound to the element that triggered the event
const [data, status, xhr] = event.detail;
console.log(data, status, xhr);
// do something ...
}).on('ajax:error', '.my_spiffy_form', function(event){
const $form = $(this); // this is bound to the element that triggered the event
const [data, status, xhr] = event.detail;
console.log(data, status, xhr);
// do something ...
});

这个处理程序是幂等的,因为它在事件冒泡到DOM顶部时捕获事件。jQuery.on的第二个可选参数是用于筛选元素的选择器。

请参阅涡轮链接:使转换成为永恒。

还要注意,传递给事件处理程序的参数是不同的,这取决于您使用的Rails版本:

Rails 5.1引入了Rails uj,并将jQuery作为依赖项删除。[…]与带有jQuery的版本不同,所有自定义事件只返回一个参数:event。在这个参数中,有一个附加的包含一组额外参数的属性详细信息。

  • Rails指南:在Rails中使用JavaScript

旧jquery ujs处理程序的签名是:

$(document).on('ajax:success', '.my_spiffy_form', function(event, data, status, xhr){
const $form = $(this); // this is bound to the element that triggered the event
console.log(data, status, xhr);
// do something ...
})

最新更新