3

我对 jquery 不太了解,也许这个标题并不能很好地解释我想要做什么,但这里是:

$.ajax({
    url: 'my_action',
    dataType: 'script',
    beforeSend: function() { //can i not just call a script here instead?
        if (1 == 1) //just an example
        {
            return false
        }
    },
    complete: function() {
        console.log('DONE');
    }
});​

所以在beforeSend,我想调用一个脚本而不是有一个内联函数。这是因为我的函数很长,它使我的 ajax 代码看起来很乱。

那可能吗?

4

2 回答 2

5
$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : foo // where foo is a function name.

示例:

function foo(){
    // Do your magic here.
}
于 2012-06-19T10:26:39.137 回答
2

如下重写您的请求以在 Ajax 调用之前加载外部 JavaScript 文件。

$.ajax({
    url: 'my_action',
    dataType: 'script',
    beforeSend: function() {
        $.getScript("/path/to/script.js", function() {
            // you can call any function from the loaded file
            console.log('DONE');
        });
    }
});​
于 2012-06-19T10:35:17.780 回答