简体   繁体   English

EJS脚本无法在Ajax“成功”调用中执行

[英]EJS Script unable to execute within ajax 'success' call

I have an EJS page that is using AJAX to retrieve some data. 我有一个使用AJAX检索一些数据的EJS页面。 after loading the data, I want to append certain content to a div. 加载数据后,我想将某些内容附加到div。 In the appended content, there are checkboxes that uses the following script: 在附加的内容中,有使用以下脚本的复选框:

<script>
$('#selectall').change(function () {
    $('.checkbox').prop('checked', this.checked).trigger('change');
});
</script>

Here is my ajax: 这是我的ajax:

$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:3000/mytableajax',
success: function(result) {
    //result is printed, everything is retrieved correctly
    $('#mytable').empty(); 
    var eventresult = JSON.parse(result);
    var node = document.getElementById('mytable');

    toAppend += '<input type="checkbox" id="selectall" class="c-check">'; //This checkbox will allow me to select all other checkboxes

    //I have other checkboxes appended at the bottom with the class "checkbox"


    node.innerHTML = toAppend;
    document.getElementById('mytable').appendChild(node);
})

When i first access the page, the select all function works. 当我第一次访问该页面时,全选功能起作用。 However, when the data is being changed using AJAX as shown in the above code, the select all function stop working. 但是,当如上述代码所示使用AJAX更改数据时,全选功能将停止工作。 I figured that my script seems to be unable to execute within the 'success' callback of AJAX, as all my functions that uses script seem to fail after changing/appending using AJAX. 我发现我的脚本似乎无法在AJAX的“成功”回调中执行,因为使用AJAX更改/追加后,所有使用脚本的函数似乎都失败了。

Is there any way to execute scripts within my AJAX 'success' callback? 有什么方法可以在我的AJAX“成功”回调中执行脚本? Appreciate any feedback/advice! 感谢任何反馈/建议!

I found a solution that actually works, hope it helps someone with the same issue. 我找到了一个切实可行的解决方案,希望对遇到同样问题的人有所帮助。

$(document).on('change', '#selectall' , function() {
    $(".checkbox").attr('checked', $(this).is(":checked")).trigger('change');
});

Basically, using the .on method in this format instead of .change method allows the content from AJAX to access this script. 基本上,以这种格式使用.on方法而不是.change方法,将允许AJAX中的内容访问此脚本。

Got the idea from here: https://forum.jquery.com/topic/use-on-click-do-not-work-after-ajax-call 从这里得到了这个主意: https : //forum.jquery.com/topic/use-on-click-do-not-work-after-ajax-call

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM