Javascript jQuery ajax 成功回调函数定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14754619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:47:58  来源:igfitidea点击:

jQuery ajax success callback function definition

javascriptjqueryajax

提问by tonga

I want to use jQuery ajax to retrieve data from a server.

我想使用 jQuery ajax 从服务器检索数据。

I want to put the success callback function definition outside the .ajax()block like the following. So do I need to declare the variable dataFromServerlike the following so that I will be able to use the returned data from the success callback?

我想将成功回调函数定义放在.ajax()块外,如下所示。那么我是否需要dataFromServer像下面这样声明变量,以便我能够使用从成功回调返回的数据?

I've seen most people define the success callback inside the .ajax()block. So is the following code correct if I want to define the success callback outside?

我见过大多数人在.ajax()块内定义成功回调。那么如果我想在外面定义成功回调,下面的代码是否正确?

var dataFromServer;  //declare the variable first

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData(dataFromServer)
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

回答by Alnitak

The "new" way of doing this since jQuery 1.5 (Jan 2011) is to use deferred objects instead of passing a successcallback. You should returnthe result of $.ajaxand then use the .done, .failetc methods to add the callbacks outside of the $.ajaxcall.

自 jQuery 1.5(2011 年 1 月)以来,执行此操作的“新”方法是使用延迟对象而不是传递success回调。您应该返回的结果$.ajax,然后使用.done.fail等方法来添加回调外的$.ajax呼叫

function getData() {
    return $.ajax({
        url : 'example.com',
        type: 'GET'
    });
}

function handleData(data /* , textStatus, jqXHR */ ) {
    alert(data);
    //do some stuff
}

getData().done(handleData);

This decouplesthe callback handling from the AJAX handling, allows you to add multiple callbacks, failure callbacks, etc, all without ever needing to modify the original getData()function. Separating the AJAX functionality from the set of actions to be completed afterwards is a good thing!.

回调处理与 AJAX 处理分离,允许您添加多个回调、失败回调等,而无需修改原始getData()函数。将 AJAX 功能与之后要完成的一组操作分开是一件好事!.

Deferreds also allow for much easier synchronisation of multiple asynchronous events, which you can't easily do just with success:

Deferreds 还允许更容易地同步多个异步事件,这是你不能轻易做到的 success:

For example, I could add multiple callbacks, an error handler, and wait for a timer to elapse before continuing:

例如,我可以添加多个回调、一个错误处理程序,并在继续之前等待计时器结束:

// a trivial timer, just for demo purposes -
// it resolves itself after 5 seconds
var timer = $.Deferred();
setTimeout(timer.resolve, 5000);

// add a done handler _and_ an `error:` handler, even though `getData`
// didn't directly expose that functionality
var ajax = getData().done(handleData).fail(error);

$.when(timer, ajax).done(function() {
    // this won't be called until *both* the AJAX and the 5s timer have finished
});

ajax.done(function(data) {
    // you can add additional callbacks too, even if the AJAX call
    // already finished
});

Other parts of jQuery use deferred objects too - you can synchronise jQuery animations with other async operations very easily with them.

jQuery 的其他部分也使用延迟对象 - 您可以非常轻松地将 jQuery 动画与其他异步操作同步。

回答by Cerbrus

Just use:

只需使用:

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

The successproperty requires only a reference to a function, and passes the data as parameter to this function.

success属性仅需要对函数的引用,并将数据作为参数传递给该函数。

You can access your handleDatafunction like this because of the way handleDatais declared. JavaScript will parse your code for function declarations before running it, so you'll be able to use the function in code that's before the actual declaration. This is known as hoisting.

handleData由于handleData声明的方式,您可以像这样访问您的函数。JavaScript 将在运行之前解析您的函数声明代码,因此您将能够在实际声明之前的代码中使用该函数。这称为提升

This doesn't count for functions declared like this, though:

不过,这不包括这样声明的函数:

var myfunction = function(){}

Those are only available when the interpreter passed them.

这些只有在口译员通过时才可用。

See this question for more information about the 2 ways of declaring functions

有关声明函数的 2 种方式的更多信息,请参阅此问题

回答by BinaryTox1n

I do not know why you are defining the parameter outside the script. That is unnecessary. Your callback function will be called with the return data as a parameter automatically. It is very possible to define your callback outside the sucess:i.e.

我不知道您为什么要在脚本外定义参数。那是不必要的。您的回调函数将自动以返回数据作为参数被调用。很可能在sucess:ie之外定义你的回调

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

the handleData function will be called and the parameter passed to it by the ajax function.

handleData 函数将被调用,参数由 ajax 函数传递给它。

回答by Undefined

Try rewriting your success handler to:

尝试将您的成功处理程序重写为:

success : handleData

The success property of the ajax method only requires a reference to a function.

ajax 方法的 success 属性只需要对函数的引用。

In your handleData function you can take up to 3 parameters:

在您的 handleData 函数中,您最多可以使用 3 个参数:

object data
string textStatus
jqXHR jqXHR

回答by jbl

I would write :

我会写:

var handleData = function (data) {
    alert(data);
    //do some stuff
}


function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

回答by V? Minh

after few hours play with it and nearly become dull. miracle came to me, it work.

几个小时后玩它,几乎变得沉闷。奇迹降临在我身上,它奏效了。

<pre>


var listname = [];   


 $.ajax({
    url : wedding, // change to your local url, this not work with absolute url
    success: function (data) {
       callback(data);
    }
});

function callback(data) {
      $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
             //   $('#displayImage1').append( "<img src='" + wedding + val +"'>" );
                 listname.push(val);
            } 
        });
}

function myfunction() {

alert (listname);

}

</pre>

回答by Lukas Bijaminas

You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters: Function( Object data, String textStatus, jqXHR jqXHR )

您不需要声明变量。Ajax 成功函数最多自动接受 3 个参数:Function( Object data, String textStatus, jqXHR jqXHR )

回答by Shivani Jadhav

In your component i.e angular JS code:

在您的组件中,即 Angular JS 代码:

function getData(){
    window.location.href = 'http://localhost:1036/api/Employee/GetExcelData';
}