问题描述
需要帮助.我正在编写一个返回ajax调用结果的函数,但是我没有得到任何结果,我想这是一个范围问题,但是有什么办法吗?这是我的代码:
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? 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;
};
推荐答案
您的问题是您发出的HTTP请求是异步的,并且Favorites
函数在Ajax请求返回之前返回.您将需要更改您的函数,以使其在响应返回后接受要执行的回调:
Your problem is that the HTTP request you're making is asnychronous and your Favorites
function returns before the Ajax request has come back. 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); } );
此外:约定是,仅打算用作构造函数的函数应以大写字母开头,因此您的函数最好命名为favorites
.
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
.
这篇关于返回ajax调用结果的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!