返回ajax调用结果的JavaScript函数

返回ajax调用结果的JavaScript函数

本文介绍了返回ajax调用结果的JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要帮助.我正在编写一个返回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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:00