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

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

问题描述

我想返回StudentId别处使用$ .getJSON()

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

我会想象这是同作用域,但它似乎不相同的方式工作C#确实

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

推荐答案

是啊,我的previous答案不工作,因为我没有理会你的code。 :)

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

问题是,匿名函数是一个回调函数 - 即的getJSON是一个异步操作将返回在某个不确定的时间点,因此即使变量的范围是匿名函数的外部(即闭合) ,它不会让你会觉得值就应该:

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

这是你想要的studentId由的getJSON调用将该值设置为执行任何code需要做任何的的回调函数或 回调执行后被

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天全站免登陆