Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

jquery - 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? 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;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...