JQuery回调到之前定义的函数

Ale*_*lex 4 javascript jquery

我还在学习JQuery(结果是一些JavaScript),但我似乎无法找到如何在回调中使用以前定义的函数.

说我有:

<script>
$(document).ready(function() {

function ajax_start() {
                      alert("starting...");
                      }

});
</script>
Run Code Online (Sandbox Code Playgroud)

我希望在另一个函数中使用它,例如:

<script>
$(document).ready(function() {

$.ajax({
        beforeSend: ajax_start(),
        url: "insert_part.php",
        type:"POST",
        data: "customer="+customer
  });
});
</script>
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*all 7

关.

$(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
    });
});
Run Code Online (Sandbox Code Playgroud)

你需要这样做,因为

  • ajax_start()计算执行名为的函数返回的值ajax_start,但是
  • 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
});
Run Code Online (Sandbox Code Playgroud)

或者只是声明一个命名函数,它可以执行您想要的操作,然后使用它:

function combined_function(xhr, settings) {
    ajax_start();
    other_function();
}

$.ajax({
    beforeSend: combined_function,
    url: "insert_part.php",
    type:"POST",
    data: "customer="+customer
});
Run Code Online (Sandbox Code Playgroud)

  • 最后的`,`可能会在某些浏览器中引起问题. (3认同)