weixin_33735077 2014-10-16 19:00 采纳率: 0%
浏览 18

来自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="2014-10-16 19:05:31Z" class="relativetime">5 years ago</span>.</div>
        </div>
    </aside>

I have code like this:

var array = [];
$('#next1').on('click', function(){
    var dataString='company= '+$(this).closest('.inside').find('select').val();
    $.ajax({
        //async: false,
        type:"POST",
        url:"ajax/companyInfo.php",
        data: dataString,
        success: function(response){
            array = response.split("/");
            alert(array);
        }//end success function
    });//end ajax
console.log(array);

it alerts correct array but logs empty array, means that i can't use it after success function.
YES, i have read tons of things regarding this problem (including this: How do I return the response from an asynchronous call?) and making it synchronous solves problem (U see it's commented in code), but everyone say it's very bad to use this method. so I have two questions:

1: why it alerts correct value if case is in sync. I mean it's explained that synchronous waits for response before executing another code and asynchronous doesn't, and that's why it can't catch variables to assign to array. but if it so, how can it alert them?

2:how can i modify code to make it work?

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33711647 2014-10-16 19:05
    关注

    Because it's asynchronous the log line will run before the success function. Anything you want to do after the array is populated must be done within the success function. Or within another function that is called from within the success function.

    评论

报告相同问题?

悬赏问题

  • ¥66 关于川崎机器人调速问题
  • ¥15 winFrom界面无法打开
  • ¥15 crossover21 ARM64版本安装软件问题
  • ¥15 mymetaobjecthandler没有进入
  • ¥15 mmo能不能做客户端怪物
  • ¥15 osm下载到arcgis出错
  • ¥15 Dell g15 每次打开eiq portal后3分钟内自动退出
  • ¥200 使用python编写程序,采用socket方式获取网页实时刷新的数据,能定时print()出来就行。
  • ¥15 matlab如何根据图片中的公式绘制e和v的曲线图
  • ¥15 我想用Python(Django)+Vue搭建一个用户登录界面,但是在运行npm run serve时报错了如何解决?