七度&光 2019-10-23 21:59 采纳率: 22.2%
浏览 24

从JQuery到JS变量[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
                            <span class="question-originals-answer-count">
                                (38 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2019-10-23 22:11:03Z" class="relativetime">6 months ago</span>.</div>
        </div>
    </aside>

I want the array of objects result (msg) that I get from AJAX into a JS variable (allEvents)

I thought it could be done like this:

let allEvents;

$.ajax({
   method: "GET",
   url: "https://someApiToGetData.com",
})
   .done(function (msg) {
      allEvents = msg;
   });

console.log(allEvents);

I get Undefined as a result on the console. So the part allEvents = msg; wasn't as easy as I thought.

If I try console.log(msg) I get what I want. But I just want msg in that allEvents JS variable so I can handle the results.

Is there any way to get msg into allEvents?

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33698043 2019-10-23 22:08
    关注

    An ajax request is asynchronous, which means that your last line will run before the ajax request has returned, that's why allEvents is undefined, if you modify your code to print allEvents inside done you'll see all events has the correct data.

    let allEvents;
    
    $.ajax({
       method: "GET",
       url: "https://someApiToGetData.com",
    })
       .done(function (msg) {
          allEvents = msg;
          console.log(allEvents);
       });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)