weixin_33697898 2015-06-18 11:49 采纳率: 0%
浏览 9

从函数返回,ajax [重复]

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="2015-06-18 12:25:52Z" class="relativetime">4 years ago</span>.</div>
        </div>
    </aside>

Ajax get data normal, but i dont know how return varname from if statement, with inside loop, with inside function ;). How can return var username from this statement? Thanks.

    $.ajax({
         dataType: 'json',
         url: 'example.com',
         type: 'POST',
         success: function (data) {
           for (var i = 0; i < data.users.length; i++) {
             if (user_id == data.users[i].id) {

                var username = data.users[i].username;
                return username; // !!!How can return this

                    };
                };
            }
        })

console.log(username) // error: username is not defined
</div>
  • 写回答

3条回答 默认 最新

  • weixin_33744854 2015-06-18 11:53
    关注

    By default, ajax will be executed asynchronously. This means that the result returned has to be handled in the callback:

    $.ajax({
      dataType: 'json',
      url: 'example.com',
      type: 'POST',
      success: function (data) {
        for (var i = 0; i < data.users.length; i++) {
          if (user_id == data.users[i].id) {
            var username = data.users[i].username;
            console.log(username);
          }
        }
      }
    });
    

    ajax could be executed with the async set to false but this is usually not recommended as it will lock the UI until you get the response from the server.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度