开发者

JavaScript function that returns result of ajax call

开发者 https://www.devze.com 2022-12-27 11:31 出处:网络
Help needed. Im writing a function that returns result of ajax c开发者_开发知识库all 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:

Help needed. Im writing a function that returns result of ajax c开发者_开发知识库all 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;
};


Ajax is asynchronous, i.e. when return links is executed, the callback function in success might not even have been called.

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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消