zoukankan      html  css  js  c++  java
  • JQuery 之 Ajax 异步和同步浅谈

    Ajax 同步和异步的区别

    同步是当 JS 代码加载到当前 Ajax 的时候会把页面里所有的代码停止加载,页面出现假死状态;当这个 Ajax 执行完毕后才会继续运行其他代码此时页面假死状态才会解除。反之异步则 Ajax 代码在运行时,其余的 JS 脚本依旧能够运行。


    在 Jquery 中可以通过 async 的 true 和 false 设置同步或异步,在默认的情况下是为 true 即为异步。

    接下来请看下 Sample Code:

    $.ajax({ 
    
            type: "post", 
    
            url: "path", 
    
           cache:false, 
    
           async:false, 
    
            dataType: "xml"
    
             success: function(obj){ 
    
            } 
    
    });

    async 这个属性可以相对的减少代码运行顺序问题,但是用的太多的也可能导致页面假死的次数太多,容易降低用户体验。

    参考官方给出的解释:

     http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxdataadapter/jquery-data-adapter.htm

    async 
    Boolean 
    Default: true
    
    By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
    
    success 
    Function
    
    A function to be called if the request succeeds. The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status. This is an Ajax Event.

    这里的话,当 async 默认的设置值为 true ,这种就为异步方式(如果忘记了概念,可参考文章开端简介)

    这种执行方式其实执行是有两个线程, 服务端请求一个,后面的 JS 脚本一个。

    Sample Code:

    $.ajax({  
    
              type:"POST", 
    
             url:"xx.aspx=init", 
    
               dataType:"xml", 
    
              success:function(data){   //function1()
    
                 f1(); 
    
                 f2(); 
    
            } 
    
             failure:function (data) {  
    
                alert('Failed');  
    
             }, 
    
      } 
    
      function2(); 

    在上例中,当ajax块发出请求后,他将停留function1(),等待server端的返回,但同时(在这个等待过程中),前台会去执行function2(),也就是说,在这个时候出现两个线程,我们这里暂且说为function1() 和function2()。

    当把asyn设为false时,这时ajax的请求时同步的,也就是说,这个时候ajax块发出请求后,他会等待在function1()这个地方,不会去执行function2(),知道function1()部分执行完毕。

  • 相关阅读:
    Java单例模式(Singleton)以及实现
    golang 垃圾回收机制
    MySQL索引背后的数据结构及算法原理
    简述拥塞控制的四种基本算法
    分库分表
    lvalue & rvalue
    理解linux cpu load
    android使用百度地图SDK获取定位信息
    iOSUIWebView---快停下啦,你的愚蠢的行为
    【翻译自mos文章】当/var/tmp文件夹被remove掉之后,GI crash,并启动失败,原因是ohasd can not create named pipe
  • 原文地址:https://www.cnblogs.com/byvar/p/4963020.html
Copyright © 2011-2022 走看看