weixin_33725126 2017-08-02 03:56 采纳率: 0%
浏览 21

处理ajax同步? [重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/6685249/jquery-performing-synchronous-ajax-requests" dir="ltr">jQuery: Performing synchronous AJAX requests</a>
                            <span class="question-originals-answer-count">
                                (4 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2017-08-02 04:26:44Z" class="relativetime">2 years ago</span>.</div>
        </div>
    </aside>

I have a example fetch data through ajax and do something. Condition is this function can reuseable. Can call anywhere.

<script type="text/javascript">

    function getData(value1,value2){

        $.ajax({
            url: URL,
            data:{
                email:value1,
                age:value2
            },
            async:false,
            dataType: "json",
            type: "get",
            success: function(data){

                var result;

                result = data.result;

                console.log("result:"+result);
            },
            error: function(){
            }
        });
    };

    var data;

    data = getData("email","age");

    console.log("data:"+data);
</script>

When i call ajax, result return later so data empty.I try use async false but just ok inside ajax.

How to do do javascript wait for the response and not execute any more, get the response and then continue executing. Set timeout is not good idea because it causing problems about server response speed on different servers and server to different client.

</div>
  • 写回答

2条回答 默认 最新

  • weixin_33711647 2017-08-02 04:01
    关注

    You can try this :

    function getData() {
        $.ajax({
            url: URL,
            ...
            ...
            type: 'GET',
            success : resultData
        })
    }
    
    var resultData = function (data) {
        console.log(data);
        // This will be called whenever the data is available
        // So you execute what ever you want to, once data is available
        // initiate function that is dependent on that data ....
    }
    
    getData();
    

    Note : never use async: false , because it will make all the next code to wait to execute and its never a good idea to make ajax async: false , try the callback function method. It will give you same result , without making ajax async: false, and its alot better way to do it.

    评论

报告相同问题?