Home > Web Front-end > JS Tutorial > body text

jquery ajax属性async(同步异步)示例_jquery

WBOY
Release: 2016-05-16 17:17:23
Original
953 people have browsed it

例1、jquery+ajax/" target="_blank">jquery ajax同步方式

复制代码 代码如下:

$.ajax({
url : 'test.php',
type : 'post',
async: false,//使用同步的方式,true为异步方式
data : {'act':'addvideo', 'videoname':videoname},//这里使用json对象
success : function(data){
//code here...
},
fail:function(){
//code here...
}
});

例2
复制代码 代码如下:

//javascript
function test()
{
 var a= 1;
 $.ajax({
  type   : 'GET',
  url    : 'test.php',
  data   : 'page=112',
  success:function(msg)
  {
   alert(msg);
   a= msg;
  }
 })
 alert(a);
}
//test.php
sleef('5'); //休息五分钟
echo 'in';
/*
 这个程序运行情况是  先打印1(a=1) 然后五秒过后 打印 in
 根据这个情况就可以知道 jquery 的ajax的执行流程
 因为是异步调用
 以前就是这样给一个变量赋值  不管怎么弄都是不对的。最后就发现这个问题
 参数async改为false就为同步调用 当ajax返回结果后程序才继续执行
*/
 

在这里,async默认的设置值为true,这种情况为异步方式,就是说当ajax发送请求后,在等待server端返回的这个过程中,前台会继续 执行ajax块后面的脚本,直到server端返回正确的结果才会去执行success,也就是说这时候执行的是两个线程,ajax块发出请求后一个线程 和ajax块后面的脚本(另一个线程)例:
例3
复制代码 代码如下:

$.ajax({ 
          type:"POST",
         url:"Venue.aspx?act=init",
           dataType:"html",
          success:function(result){   //function1()
             f1();
             f2();
        }
         failure:function (result) { 
            alert('Failed'); 
         },
  }
  function2();
 

在上例中,当ajax块发出请求后,他将停留function1(),等待server端的返回,但同时(在这个等待过程中),前台会去执行function2(),也就是说,在这个时候出现两个线程,我们这里暂且说为function1() 和function2()。
当把asyn设为false时,这时ajax的请求时同步的,也就是说,这个时候ajax块发出请求后,他会等待在function1()这个地方,不会去执行function2(),知道function1()部分执行完毕。
注意
同步的意思是当JS代码加载到当前AJAX的时候会把页面里所有的代码停止加载,页面出去假死状态,当这个AJAX执行完毕后才会继续运行其他代码页面假死状态解除。
而异步则这个AJAX代码运行中的时候其他代码一样可以运行。
jquery的async:false,这个属性
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!