Javascript通过数据属性中的函数名称回调

2024-03-25

我试图为 ajax 调用提供回调函数,其中函数名称保存在表单的“data-apply”属性下。

jQuery(function($) {
    $('form[data-async]').on('submit', function(event) {
        var $form = $(this);
        var $target = $($form.attr('data-target'));
        var apply = $form.attr('data-apply');
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),

            success: function(data, status) {
                var callBackFunc = new Function(apply);
                callBackFunc.call();
            }
        });

        event.preventDefault();
    });
});

function addBubble(){
    alert('a');
}

表格:

<form id="111" class="form-horizontal " data-async data-target="#rating-modal" data-apply="addBubble();"  action="/some/action/performed" method="POST">

我想避免使用eval()在这种情况下,因为eval()可能会引入安全和性能问题。没有把握Function()是一种更安全的方法,或者有一种完全不同的方法来处理这个问题。

那么是否有办法传入函数回调来处理不同的情况呢?

原始代码借自:https://gist.github.com/havvg/3226804 https://gist.github.com/havvg/3226804


由于该函数是全局定义的,因此您可以通过window object.

window["functionName"].call();

删除 addBubble 中的括号

<form id="111" class="form-horizontal " data-async data-target="#rating-modal" data-apply="addBubble"  action="/some/action/performed" method="POST">

JavaScript

jQuery(function($) {
    $('form[data-async]').on('submit', function(event) {
        var $form = $(this);
        var $target = $($form.attr('data-target'));
        var apply = $form.attr('data-apply');
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),

            success: function(data, status) {
                if(typeof window[apply] == "function")
                    window[apply].call(); //window[apply](); or window[apply].apply(); will work too
            }
        });

        event.preventDefault();
    });
});

function addBubble(){
    alert('a');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript通过数据属性中的函数名称回调 的相关文章

随机推荐