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.

    评论

报告相同问题?