我仍在学习 JQuery(因此学习了一点 JavaScript),但我似乎无法找到如何在回调中使用先前定义的函数。
假设我有:
<script>
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
});
</script>
我希望在另一个函数中使用它,例如:
<script>
$(document).ready(function() {
$.ajax({
beforeSend: ajax_start(),
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
});
</script>
这是正确的吗? (我假设不是,因为它不是......)进行回调的正确方法是什么?
最佳答案
关闭。
$(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
的计算结果为 the function itself .
编辑回复:OP 评论
"how would I include a second function in the callback. Something like- beforesend: ajax_start,other_function (obv. not exactly like that)?"
有几种方法可以做到这一点。使用匿名函数组合它们:
$.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
});
关于javascript - JQuery 回调到先前定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4691792/