从jQuery的Ajax调用指定变量返回undefined [英] Assigning variable from jquery ajax call returns undefined

查看:593
本文介绍了从jQuery的Ajax调用指定变量返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的jQuery,我想一个Ajax调用后赋值给一个变量,但它返回undefined。我的code是如下:

I am new to jquery and I am trying to assign a value to a variable after an ajax call but it returns undefined. My code is below:

function prepareDocument() {
var a = getAverageRating(1);
alert(a);
}
function getAverageRating(pageId) {
$.ajax({
    url: "../services/rating.ashx?action=getAverageRating&pageId=" + pageId,
    dataType: "text",
    type: "GET",
    data: {},
    error: function (err) {
        displayDialogBox("Error", err.toString());
    },
    success: function (data) {
        return data;
    }
});
}

任何帮助将是AP preciated。 谢谢你,

Any help would be appreciated. Thanks,

推荐答案

这是对于不习惯使用异步操作的人一个非常普遍的问题。它要求你重新思考如何构建你的code,因为你不能只是计划在正常顺序的风格。

This is a very common problem for people not used to using asynchronous operations. It requires you to rethink how you structure your code because you can't just program in normal sequential style.

您无法从异步Ajax调用成功处理程序返回一个值。阿贾克斯CLL早已完成,并已经返回。从成功处理程序返回一个值,只是进入的AJAX code,不回你的code大便。

You cannot return a value from the success handler of an asynchronous ajax call. The ajax cll has long since completed and already returned. Returning a value from the success handler just goes into the bowels of the ajax code, not back into your code.

相反,你必须使用的成功处理程序或您从成功处理程序调用一个函数Ajax调用的结果。

Instead, you must use the results of the ajax call in the success handler or in a function you call from the success handler.

在特定的情况下,你的 getAverageRating()功能可能需要采取一个回调函数,当评级被检索,回调函数将会被调用。因为它会立即然后返回一些在未来的时间,不能返回值,Ajax调用完成并成功处理的AJAX调用函数与实际数据。

In your specific case, your getAverageRating() function probably needs to take a callback function and when the rating has been retrieved, the callback function will be called. It cannot return the value because it returns immediately and then some time in the future, the ajax call completes and the success handler in the ajax function is called with the actual data.

function prepareDocument() {
    getAverageRating(1, function(data) {
        alert(data);
    });
}

function getAverageRating(pageId, fn) {

    $.ajax({
        url: "../services/rating.ashx?action=getAverageRating&pageId=" + pageId,
        dataType: "text",
        type: "GET",
        data: {},
        error: function (err) {
            displayDialogBox("Error", err.toString());
        },
        success: function (data) {
            fn(data);
        }
    });

}

这篇关于从jQuery的Ajax调用指定变量返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆