通过数据属性中的函数名称进行Java语言回调 [英] Javascript call back by function name in data attribute
问题描述
我正在尝试为ajax调用提供回调函数,该函数名保存在表单的数据应用"属性下.
I am trying to provide a call back function for an ajax call, where the function name is saved under the "data-apply" attribute of a form.
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()
是一种更安全的方法,还是有完全不同的方法来处理此问题.
I want to avoid using eval()
in this case, since eval()
might introduce security and performance issues. Not sure Function()
is a safer method or there is a completely different way to handle this.
那么反正有传递函数回调以处理不同情况的情况吗?
So is there anyway to pass in a function callback in order to handle difference situations?
原始代码是借来的: https://gist.github.com/havvg/3226804
推荐答案
由于该函数是全局定义的,因此可以通过window
对象调用它.
Since the function is globally defined, you can call it through the window
object.
window["functionName"].call();
从addBubble删除括号
Remove the parentheses from addBubble
<form id="111" class="form-horizontal " data-async data-target="#rating-modal" data-apply="addBubble" action="/some/action/performed" method="POST">
JavaScript
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');
}
这篇关于通过数据属性中的函数名称进行Java语言回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!