JQuery 回调先前定义的函数

2023-12-07

我仍在学习 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>

这是正确的吗? (我认为不是,因为它没有......)进行回调的正确方法是什么?


Close.

$(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()评估为值returned通过执行名为的函数ajax_start, but
  • ajax_start评估为函数本身.

编辑回复:OP评论

“我如何在回调中包含第二个函数。类似 - beforesend: 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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JQuery 回调先前定义的函数 的相关文章

随机推荐