加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax的原理和应用

发布时间:2020-12-15 21:51:39 所属栏目:百科 来源:网络整理
导读:一、什么是AJAX AJAX(Asynchronous JavaScript and XML)异步的 JavaScript 和 XML,通过与后端接口交互,实现页面中局部刷新。 二、AJAX原理 AJAX是通过XMLHttpRequest(所有现代浏览器均支持 XMLHttpRequest 对象,IE5 和 IE6 使用 ActiveXObject)与服务

一、什么是AJAX

AJAX(Asynchronous JavaScript and XML)异步的 JavaScript 和 XML,通过与后端接口交互,实现页面中局部刷新。

二、AJAX原理

AJAX是通过XMLHttpRequest(所有现代浏览器均支持 XMLHttpRequest 对象,IE5 和 IE6 使用 ActiveXObject)与服务器交互,获取数据后通过javascript操作DOM来显示数据。

三、XMLHttpRequest对象

1、创建XMLHttpRequest对象

functioncreateXHR(){
varxmHttp=null;
if(window.XMLHttpRequest){
xmlHttp=newwindow.XMLHttpRequest();
}else{
xmlHttp=newwindow.ActiveXObject('Microsoft.XMLHTTP');
}
returnxmlHttp;
}

2、向服务器发送请求

向服务器发送请求,要使用XMLHttpRequest的open和send方法


open()方法,规定请求的类型、URL、是否异步请求

open(method,url,async)

mehtod:请求的类型(POST或GET)

url:请求的URL

anync:是否是异步请求,true(异步)、false(同步),默认为异步请求


send()方法,将请求发送到服务器

send(string)

string:仅用于POST请求,发送请求所带的参数


发送GET请求

varxmlHttp=createXHR();
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
varresult=xmlHttp.responseText;
//对应的处理逻辑
}
}
xmlHttp.open('GET','test.php?aa=aa&bb=bb',true);
xmlHttp.send();

发送POST请求

varxmlHttp=createXHR();
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
varresult=xmlHttp.responseText;
//对应的处理逻辑
}
}
xmlHttp.open('POST','test.php',true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send('aa=aa&bb=bb');

使用POST方式发送请求时,需要设置http头信息,通过send方法传递要发送的参数

当请求是异步请求时 ,需要通过onreadystatechange事件注册一些响应后的操作,如果是同步请求,只需要在send方法后直接调用xmlHttp.responseText,不需要注册onreadystatechange

onreadystatechange:每当readyState发生改变时,都会触发该事件

readyState:存储XMLHttpRequest的状态,从0到4发生变化

  • 0: 请求未初始化

  • 1: 服务器连接已建立

  • 2: 请求已接收

  • 3: 请求处理中

  • 4: 请求已完成,且响应已就绪

status:从服务器端返回的响应代码,比如200(就绪),404(未找到)

responseText:从服务器返回的字符串数据

responseXML:从服务器返回的XML数据,需要作为XML对象解析

四、完整实例

php代码,test.php

<?php
$uname=$_GET('uname');
$age=$_GET('age');
$result=array(
'uname'=>$uname,'age'=>$age
);
echojson_encode($result);
?>

javascript代码:

functioncreateXHR(){
varxmHttp=null;
if(window.XMLHttpRequest){
xmlHttp=newwindow.XMLHttpRequest();
}else{
xmlHttp=newwindow.ActiveXObject('Microsoft.XMLHTTP');
}
returnxmlHttp;
}
varxmlHttp=createXHR();
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
varresult=xmlHttp.responseText;
alert(result);
}
}
xmlHttp.open('GET','test.php?uname=kaixin&age=16',true);
xmlHttp.send();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读