jQuery ajax success callback function definition

2018-12-31 23:40发布

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

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

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?

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
}

8条回答
大哥的爱人
2楼-- · 2019-01-01 00:19

Try rewriting your success handler to:

success : handleData

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

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

object data
string textStatus
jqXHR jqXHR
查看更多
何处买醉
3楼-- · 2019-01-01 00:20

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

查看更多
登录 后发表回答