从 jquery ajax 调用分配变量返回未定义

2022-01-19 00:00:00 return callback jquery ajax

我是 jquery 的新手,我试图在 ajax 调用后为变量赋值,但它返回未定义.我的代码如下:

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

任何帮助将不胜感激.谢谢,

Any help would be appreciated. Thanks,

推荐答案

对于不习惯使用异步操作的人来说,这是一个很常见的问题.它要求您重新考虑如何构建代码,因为您不能只以正常的顺序样式进行编程.

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 调用的成功处理程序返回值.ajax cll 早就完成并且已经返回.从成功处理程序返回一个值只会进入 ajax 代码的内部,而不是返回到您的代码中.

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

}

相关文章