JQuery回调到之前定义的函数
我还在学习JQuery(结果是一些JavaScript),但我似乎无法找到如何在回调中使用以前定义的函数。
说我有:
$(document).ready(function() { function ajax_start() { alert("starting..."); } });
我希望在另一个函数中使用它,例如:
$(document).ready(function() { $.ajax({ beforeSend: ajax_start(), url: "insert_part.php", type:"POST", data: "customer="+customer }); });
这是正确的吗? (我假设不是因为它没有……)进行回调的正确方法是什么?
关。
$(document).ready(function() { function ajax_start() { alert("starting..."); } $.ajax({ beforeSend: ajax_start, // <== remove the parens url: "insert_part.php", type:"POST", data: "customer="+customer // <== as Skilldrick pointed out, // remove the trailing comma as well }); });
你需要这样做,因为
-
ajax_start()
计算为执行名为ajax_start
的函数返回的值,但是 -
ajax_start
计算函数本身 。
编辑重新:OP评论
“我将如何在回调中包含第二个函数。像之前的那样:ajax_start,other_function(obv。不完全那样)?”
有几种方法可以做到这一点。 使用匿名函数组合它们:
$.ajax({ // if you need the arguments passed to the callback beforeSend: function (xhr, settings) { ajax_start(); other_function(); }, url: "insert_part.php", type:"POST", data: "customer="+customer });
或者只是声明一个命名函数,它可以执行您想要的操作,然后使用它:
function combined_function(xhr, settings) { ajax_start(); other_function(); } $.ajax({ beforeSend: combined_function, url: "insert_part.php", type:"POST", data: "customer="+customer });
将ajax_start
的值更改为ajax_start
。 换句话说,删除括号。
使用括号,您将调用ajax_start()
并将ajax_start()
设置为ajax_start()
的返回值(在这种情况下,我相信这将是undefined
)。
只需删除括号,然后引用’function’对象。 ()调用该函数,因此您将传递ajax_start的返回值。
$.ajax({ beforeSend: ajax_start, url: "insert_part.php", type:"POST", data: "customer="+customer, }); });