支持异步(async)请求是ajax的重要特性。
示例的文件结构如下:
client.html源码:
<!DOCTYPE html> <head> <title>ajax_async_demo_by_xqoffice</title> <style> p,div {border: 1px solid gray;width: 100px;} button {margin-top: 18px;} </style> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('button').click(function(){ $.ajax({ "type":"POST", "url":"server.php", "data":"id=1&var2=val2", "beforeSend":function(){ $('#p1').html('<img src="icon/running.gif" />'); }, "success":function(backdata){ $('#p1').html('<img src="icon/done.png" />'); $('#div1').html(backdata); }, "error":function(){ $('#p1').html('<img src="icon/error.png" />'); } }); $.ajax({ "type":"POST", "url":"server.php", "data":"id=2&var2=val2", "beforeSend":function(){ $('#p2').html('<img src="icon/running.gif" />'); }, "success":function(backdata){ $('#p2').html('<img src="icon/done.png" />'); $('#div2').html(backdata); }, "error":function(){ $('#p2').html('<img src="icon/error.png" />'); } }); }); }); </script> </head> <body> <p id='p1'>p1</p> <div id='div1'>div1</div> <p id='p2'>p2</p> <div id='div2'>div2</div> <button>Submit</button> </body> </html>
server.php代码:
<?php $id=$_POST['id']; if ($id==1){ sleep(5); echo 'one'; } else { sleep(2); echo 'two'; } ?>
效果:发起两个请求之后,请求2的响应反倒比请求1的先完成,和响应1完成与否无关。