从 $.each 匿名函数获取变量值
这是我的 AJAX 成功回调:
success: function(data){
var uD = '<ul class="user-details">';
$.each(data['user details'], (function(key,val){
uD += '<li><label>' + key + ':</label><span>' + val + '</span></li>';
});
uD += '</ul>';
return uD;
}
数据是一个 JSON 对象。
正如您所看到的,我正在尝试从 JSON 对象构建一个列表,但是当我返回变量 uD
时,它是未定义的。如何获取超出 $.each 函数范围的 uD
值?
编辑:抱歉,我应该指定。 return 语句仅位于 AJAX 回调中,因为 AJAX 调用位于另一个函数内(需要返回某些内容)。由于它是异步的,我无法在 AJAX 调用“之后”返回,它必须位于回调中。
This is my AJAX success callback:
success: function(data){
var uD = '<ul class="user-details">';
$.each(data['user details'], (function(key,val){
uD += '<li><label>' + key + ':</label><span>' + val + '</span></li>';
});
uD += '</ul>';
return uD;
}
data is a JSON object.
As you can see, I'm trying to build a list out of the JSON object, but by the time I return the variable uD
, it's undefined. How can I get the value of uD
past the scope of the $.each function?
Edit: Sorry, I should have specified. The return statement was only in the AJAX callback because the AJAX call is within another function (which needs to return something.) Since it's async, I couldn't return 'after' the AJAX call, it had to be in the callback.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法从 Ajax 回调返回数据。我猜您想将已内置的
UL
插入到 DOM 中,因此您应该在 Ajax 回调函数中执行此操作。指定要插入的元素或使用任何其他 DOM 插入函数,而不是
body
。使用异步 AJAX 调用,您无法真正
返回
内容。所以你不能做类似的事情From an Ajax callback, you cannot return data. I guess you want to insert the
UL
you have built into the DOM, so you should do it inside your Ajax callback function.Instead of
body
specify the element you want to insert it into or use any other DOM Insertion functions.With asynchronous AJAX calls you cannot really
return
things. So you cannot do things like如果您在 AJAX 调用之前创建一个变量,并在
success
函数内部为其设置一个值,您将能够在代码的任何其他部分。编辑
根据您的评论(您需要从函数返回此值),对此函数的所有调用都需要等待它响应。然后,我建议您关闭
async
。If you create a variable before your AJAX call and set a value to it inside the
success
function, you will be able to read it variable on any other part of you code.EDIT
Based on your comment (you need to return this value from a function), all your calls to this function needs wait it response. Then, I suggest you to turn off
async
.