AJAX

同步&异步

  • 同步:同一个时间点允许执行多个进程
  • 异步:同一个时间点只允许执行一个进程

案例一

接收/处理JSON信息

function getWeather(){ var xhr=new XMLHttpRequest(); // console.log(xhr); xhr.onreadystatechange=function() { if(xhr.readyState==4 && xhr.status==200){ // 通过eval()把接收的JSON字符串变成真实的对象信息 eval("var info="+xhr.responseText); console.log(info); console.log(info.city); } } xhr.open('get','test.php',true); xhr.send(null); }

案例二

校验用户名(get)

用户名:

function checkName(){ var un=document.getElementById('username').value; // GET方式:需对传递的特殊符号(如:&、=)或中文进行编码处理 un=encodeURIComponent(un); var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function() { if(xhr.readyState==4 && xhr.status==200){ alert(xhr.responseText); } } xhr.open('get','test.php?name='+un,true); xhr.send(null); }

案例三

校验用户名(post)

用户名:

function checkName(){ var un=document.getElementById('username').value; // POST:传递的中文信息无需编码,特殊符号仍需编码 un=encodeURIComponent(un); var info="name="+un; var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function() { if(xhr.readyState==4 && xhr.status==200){ alert(xhr.responseText); } } xhr.open('post','test.php',true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send(info); }

案例四

传统分页效果:连接数据库、获得数据、分页显示
http://网址/data.php?page=1
http://网址/data.php?page=2
http://网址/data.php?page=3
xhr.open('get','data.php?page=3',true);

缓存

浏览器对动态程序文件缓存的处理解决:
1.给请求的地址设置随机数(保证每次请求的地址都不一样)【推荐】;
xhr.open('get','test.php?'+Math.random(),true);
2.给动态程序设置header头信息,静止浏览器对其缓存。
header()

结束语

如果喜欢本文,记得点赞并加关注哟。

你可能感兴趣的:(AJAX)