javascript 如何从 Rest API 获取 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10520871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get JSON data from Rest APi
提问by InfoLearner
I am creating an object in javascript:
我正在用 javascript 创建一个对象:
var t = null;
$.getJSON('http://localhost:53227/Home/GetData', function (data) {
alert(data);
t = data;
});
alert(t);
When I alert data, I get an object back. When I alert t, it's null.
当我提醒数据时,我会返回一个对象。当我提醒 t 时,它为空。
Can you please guide, how to set "t" to the returned data?
你能指导一下,如何将“t”设置为返回的数据?
回答by Madbreaks
This will work as expected - the issue is not that t
is not set, it's that you're doing alert(t)
before the getJSON
callback is executed. Try doing alert(t)
immediately after t = data;
这将按预期工作 - 问题不是t
未设置,而是您在执行回调alert(t)
之前getJSON
正在执行的操作。尝试alert(t)
后立即执行t = data;
In other words, here's your current order of operations:
换句话说,这是您当前的操作顺序:
- Set t = null
- Call server script
- alert(t) --> t is still null!
- (some amount of time later) receive JSON response
- alert data
- set t = data
- 设置 t = null
- 调用服务器脚本
- alert(t) --> t 仍然为空!
- (一段时间后)接收 JSON 响应
- 警报数据
- 设置 t = 数据
...as you can see, at step 3 't' will still be null. Try this instead:
...如您所见,在第 3 步 't' 仍将为空。试试这个:
var t = null;
$.getJSON('http://localhost:53227/Home/GetData', function (data) {
alert(data);
t = data;
alert(t);
});
Cheers
干杯