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.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器