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()部分执行完毕。

  • 相关阅读:
    结构体、共用体
    strlen函数,strcat函数,strcpy函数,strncpy函数,strcmp函数
    memmove函数
    Spring Boot——2分钟构建spring web mvc REST风格HelloWorld
    maven3常用命令、java项目搭建、web项目搭建详细图解
    C++中的const关键字
    Pyp 替代sed,awk的文本处理工具
    Python 中的进程、线程、协程、同步、异步、回调
    Python-aiohttp百万并发
    学习Python的三种境界
  • 原文地址:https://www.cnblogs.com/byvar/p/4963020.html
Copyright © 2011-2022 走看看