[英]JavaScript function that returns result of ajax call
Help needed. 需要帮助。 Im writing a function that returns result of ajax call but i did not get any results, i guess it's a scope issue, but is there any way to do it?
我正在写一个函数返回ajax调用的结果,但我没有得到任何结果,我想这是一个范围问题,但有什么办法可以做到吗? Here is my code:
这是我的代码:
function Favorites() {
var links;
$.ajax({
type: "GET",
url: "/Services/Favorite.svc/Favorites",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
links = (typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
}
});
return links;
};
Ajax is asynchronous, ie when return links
is executed, the callback function in success
might not even have been called. Ajax是异步的,即当执行
return links
时,甚至可能都没有调用success
的回调函数。
Extend your function to accept a callback: 扩展您的函数以接受回调:
function Favorites(callback) {
var links;
$.ajax({
type: "GET",
url: "/Services/Favorite.svc/Favorites",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: callback
});
};
and call it with: 并称之为:
var callback = function(msg) {
links = (typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
// do other stuff with links here
}
Favorites(callback);
Your problem is that the HTTP request you're making is asnychronous and your Favorites
function returns before the Ajax request has come back. 您的问题是您正在进行的HTTP请求是异步的,并且您的
Favorites
函数在Ajax请求返回之前返回。 You will need to change your function so that it accepts a callback to be executed once the response has come back: 您将需要更改您的函数,以便它接受响应返回后执行的回调:
function Favorites(callback) {
$.ajax({
type: "GET",
url: "/Services/Favorite.svc/Favorites",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
var links = (typeof msg.d == 'string') ? eval('(' + msg.d + ')') : msg.d;
callback(links);
}
});
};
Favorites( function(links) { alert(links); } );
Aside: convention is that only functions intended to be used as constructors should start with a capital letter, so your function would be better named as favorites
. 除此之外:约定是只有用作构造函数的函数才能以大写字母开头,因此您的函数最好命名为
favorites
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.