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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:08:51  来源:igfitidea点击:

How do I get JSON data from Rest APi

javascriptajaxjson

提问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 tis not set, it's that you're doing alert(t)before the getJSONcallback 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:

换句话说,这是您当前的操作顺序:

  1. Set t = null
  2. Call server script
  3. alert(t) --> t is still null!
  4. (some amount of time later) receive JSON response
  5. alert data
  6. set t = data
  1. 设置 t = null
  2. 调用服务器脚本
  3. alert(t) --> t 仍然为空!
  4. (一段时间后)接收 JSON 响应
  5. 警报数据
  6. 设置 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

干杯