如何从 $.getJSON 函数返回变量 [英] How can I return a variable from a $.getJSON function

查看:42
本文介绍了如何从 $.getJSON 函数返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回 StudentId 以在 $.getJSON()

范围 之外的其他地方使用

j.getJSON(url, data, function(result){var studentId = result.Something;});//这里使用studentId

我认为这与范围界定有关,但它的工作方式似乎与 c# 不同

解决方案

是的,我之前的回答不起作用,因为我没有注意你的代码.:)

问题在于匿名函数是一个回调函数 - 即 getJSON 是一个异步操作,它将在某个不确定的时间点返回,所以即使变量的范围在该匿名函数之外(即闭包),它不会具有您认为应有的价值:

var studentId = null;j.getJSON(网址,数据,功能(结果){studentId = result.Something;});//studentId 在这里仍然为空,因为这一行//在将其值设置为 result.Something 的行之前执行

您想要使用 getJSON 调用设置的 studentId 值执行的任何代码都需要在回调函数或回调执行后发生.>

I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()

j.getJSON(url, data, function(result)
{
    var studentId = result.Something;
});

//use studentId here

I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does

解决方案

Yeah, my previous answer does not work because I didn't pay any attention to your code. :)

The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:

var studentId = null;
j.getJSON(url, data, function(result)
{
    studentId = result.Something;
});

// studentId is still null right here, because this line 
// executes before the line that sets its value to result.Something

Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.

这篇关于如何从 $.getJSON 函数返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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