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.

    评论

报告相同问题?