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 dataFromServer
like 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
}
7 个解决方案
#1
76
Just use:
只使用:
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
The success
property requires only a reference to a function, and passes the data as parameter to this function.
成功属性只需要对函数的引用,并将数据作为参数传递给这个函数。
You can access your handleData
function like this because of the way handleData
is 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
166
The "new" way of doing this since jQuery 1.5 (Jan 2011) is to use deferred objects instead of passing a success
callback. You should return the result of $.ajax
and then use the .done
, .fail
etc methods to add the callbacks outside of the $.ajax
call.
自jQuery 1.5(2011年1月)以来,“新”的方法是使用延迟对象,而不是传递成功回调。您应该返回$的结果。然后使用.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 decouples the 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:
延迟也允许多个异步事件的同步化,这是不容易成功的:
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动画与其他异步操作同步。
#3
11
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.
我不知道为什么要在脚本外部定义参数。这是不必要的。您的回调函数将会自动地以返回数据作为参数调用。很有可能在成功之外定义回调:即。
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函数传递给它的参数。
#4
5
Try rewriting your success handler to:
试着重写你的成功处理器:
success : handleData
The success property of the ajax method only requires a reference to a function.
ajax方法的成功属性只需要引用一个函数。
In your handleData function you can take up to 3 parameters:
在你的handleData函数中,你最多可以取3个参数:
object data
string textStatus
jqXHR jqXHR
#5
3
I would write :
我想写:
var dataFromServer; //declare the variable first
var handleData = function (data) {
alert(data);
//do some stuff
}
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
#6
1
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个参数:函数(对象数据、字符串textStatus、jqXHR jqXHR)
#7
1
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>
#1
76
Just use:
只使用:
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
The success
property requires only a reference to a function, and passes the data as parameter to this function.
成功属性只需要对函数的引用,并将数据作为参数传递给这个函数。
You can access your handleData
function like this because of the way handleData
is 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
166
The "new" way of doing this since jQuery 1.5 (Jan 2011) is to use deferred objects instead of passing a success
callback. You should return the result of $.ajax
and then use the .done
, .fail
etc methods to add the callbacks outside of the $.ajax
call.
自jQuery 1.5(2011年1月)以来,“新”的方法是使用延迟对象,而不是传递成功回调。您应该返回$的结果。然后使用.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 decouples the 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:
延迟也允许多个异步事件的同步化,这是不容易成功的:
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动画与其他异步操作同步。
#3
11
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.
我不知道为什么要在脚本外部定义参数。这是不必要的。您的回调函数将会自动地以返回数据作为参数调用。很有可能在成功之外定义回调:即。
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函数传递给它的参数。
#4
5
Try rewriting your success handler to:
试着重写你的成功处理器:
success : handleData
The success property of the ajax method only requires a reference to a function.
ajax方法的成功属性只需要引用一个函数。
In your handleData function you can take up to 3 parameters:
在你的handleData函数中,你最多可以取3个参数:
object data
string textStatus
jqXHR jqXHR
#5
3
I would write :
我想写:
var dataFromServer; //declare the variable first
var handleData = function (data) {
alert(data);
//do some stuff
}
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
#6
1
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个参数:函数(对象数据、字符串textStatus、jqXHR jqXHR)
#7
1
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>