Ajax交互方式
- Ajax:Asynchronous JavaScript And XML(异步JavaScript和XML):它是一种局部刷新技术,是用来改善用户体验的。
发送请求实现步骤
-
获取ajax核心对象XMLHttpRequest;
-
准备发送请求:xhr.open(“get/post”,"/xx/add",true);
-
设置回调函数(主要是获取服务器返回的正确数据):
xhr.onreadystatechange = function(){ If(xhr.readyState == 4 && xhr.status==200){ ...... } }
-
拼装参数 var param = ”p1=v1&p2=v2”; var param = {“p1”:v1,”p2”:v2}
-
发送请求:xhr.send()
-
发送get请求:
function getTime(){ //使用ajax的步骤: //1、准备ajax的核心对象,XMLHttpRequest var xhr; try{ xhr = new XMLHttpRequest(); }catch(e){ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //2、发送前的准备工作:1、请求方式(GET还是POST) 2、请求的url 3、是否异步(true是异步,false是同步) xhr.open("GET","/ajax/getTimer",true); //3、做xhr状态码变更的监听 xhr.onreadystatechange = function(){ //当xhr的状态变成4并且stats是200的时候,获取结果 if(xhr.readyState == 4 && xhr.status == 200){ var div = document.getElementById("myDiv"); div.innerText = xhr.responseText; } } //4、发送请求 xhr.send(); //常见的http状态码: //200 请求成功并且返回了 //404 资源不存在 //500 服务器报错了 //400 错误的请求(一般发生在参数错误) }
-
发送post请求:
-
设置请求头:
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
-
代码:
function login(){ //1、构建ajax的核心对象 XMLHttpRequest var xhr; try{ xhr = new XMLHttpRequest(); }catch(e){ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //2、发送前的准备工作 xhr.open("POST","/ajax/login",true); //3、监听函数 onreadystatechange xhr.onreadystatechange=function(){ //4、返回结果的处理 //当xhr的状态变成4并且stats是200的时候,获取结果 if(xhr.readyState == 4 && xhr.status == 200){ //判断responseText返回的是true还是false var text = xhr.responseText; if("true" == text){ //跳转到成功页面 location.href="success.html"; }else { alert("登陆失败,用户名或密码错误"); } } } //处理参数 var username = document.getElementById("username"); username = username.value; var password = document.getElementById("password"); password = password.value; var param="username="+username+"&password="+password; //POST请求需要设置请求头,表示参数是普通文本 xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //如果有参数,参数写在send函数里面,只有post请求才能传递参数 xhr.send(param); }
-