Assigning variable from jquery ajax call returns undefined(从 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);
}
});
}
这篇关于从 jquery ajax 调用分配变量返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 jquery ajax 调用分配变量返回未定义


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01