what is Ajax?
全名叫做 Asynchronous javascript and xml
往名字一看的话, 就是 Asynchronous (异步) javascript and(和) xml(一种传输格式),
用JavaScript 以 异步的形式操作 xml (以前传数据 用的是 xml, 现在用的是 json)
ajax :一种不用刷新整个页面便可与服务器通讯的办法。
下面的案例,没有刷新页面
先来了解一下,ajax 的一些参数:
传输的类型: 一般常用的 有 GET 和 POST。
POST传输数据时,不需要在URL中显示出来,而GET方法要在URL中显示,受URL限制长度限制 最多只能传递大约1024字节.
GET:顾名思义,从服务器取东西。所以他也只能取东西,
POST:把数据传给服务器,传输的数据可达2M
open:open('传输类型', 'url', true) true 决定了你要不要异步。 没有特殊要求, 都是异步
send:send() 发送请求。 类型为 POST 的时候, 把希望发送的数据放到 send(这里)
readyState:对象状态 ↓
0 = 未初始化,未调用 send() 方法。
1 = 读取中,已调用 send() ,正在发送请求。
2 = 已读取,send() 方法执行完成,接收到全部响应内容
3 = 交互中,正在解析响应内容
4 = 完成,响应内容解析完成。
每当readyState 改变的时候, 就会触发 onreadystatechange 事件,所以我们需要监听onreadystatechange 事件,等他等于 4 的时候,说明我们请求完成了
status: 当我们从客户端向服务器发送请求时,服务器向我们返回状态码 例如↓
1xx: 服务器正在请求中
2xx:请求已正常处理完毕
3xx:资源位置不正常
4xx:客户端出错
5xx:服务器错误
200:成功
304:资源未被修改
403:表示你的请求被服务器拒绝了
等等,等遇到再去百度查就可以。所以,我们只需要判断 是不是等于 200 即可。
setRequestHeader:当类型为 POST的时候, 需要使用 setRequestHeader 来添加 编码。 规定在发送表单数据之前如何对其进行编码, application/x-www-form-urlencoded (默认), multipart/form-data (<input type='file'>) 不对字符编码。在使用包含文件上传控件的表单是,必须使用该值。
responseText : 获取字符串形式的响应数据。
本次演示,使用的是本地的服务器。
如何使用 ajax 对象,利用ajax 获取数据
第一步: 创建 ajax 对象 new XMLHttpRequest()
ie 没有这个方法,但是他有 new ActiveXObjcet('Microsoft.XMLHTTP')
// 创建ajax对象 var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else { //为了兼容IE6 xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
第二步,调用 open 和 send
传入 类型, 和 url 和 决定异步否的 布尔值
xhr.open('GET', './getNews', true);
// xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); 此次使用GET 所以不需要设置编码 xhr.send();
第三步,监听 onreadystatechange 事件,判断时候 请求回来
xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ console.log(JSON.parse(xhr.responseText)) //响应数据 转成 json 格式,好让我们使用。 } }
下面封装 ajax 函数。
function myAjax (options){ this.method = options.method; this.url = options.url; this.data = options.data || ''; this.flag = options.flag || true; this.callback = options.callback; var self = this; var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHttp'); } if(this.method == 'GET' || this.method == 'get'){ xhr.open('GET', this.url + "?" + this.data, this.flag); xhr.send(); }else{ xhr.open('POST', this.url, this.flag); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xhr.send(this.data); } xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ if(self.method == 'GET' || self.method == 'get'){ self.callback(JSON.parse(xhr.responseText)); }else{ self.callback(xhr.responseText); } } } }
封装好后, 测试一下
测试两种 类型 GET 和 POST
效果如下:
详细代码在效果图下面
html代码如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <form> <input type="text" name="username" id="username"> <input type="text" name="age" id="age"> <input type="submit" id="submit"> </form> <button type="" id="getNews">获取新闻</button> <ul id="newsList"></ul> <script src="./index.js"></script> </body> </html>
js代码如下:
function myAjax (options){ this.method = options.method; this.url = options.url; this.data = options.data || ''; this.flag = options.flag || true; this.callback = options.callback; var self = this; var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHttp'); } if(this.method == 'GET' || this.method == 'get'){ xhr.open('GET', this.url + "?" + this.data, this.flag); xhr.send(); }else{ xhr.open('POST', this.url, this.flag); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xhr.send(this.data); } xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ if(self.method == 'GET' || self.method == 'get'){ self.callback(JSON.parse(xhr.responseText)); }else{ self.callback(xhr.responseText); } } } } document.getElementById('getNews').onclick = function(){ myAjax ({ method: 'GET', url: './getNews.php', callback: news, }) } document.getElementById('submit').onclick = function(e){ e.preventDefault(); var user = document.getElementById('username'); var age = document.getElementById('age'); var str = user.name + '=' + user.value + '&' + age.name + '=' + age.value; myAjax ({ method: 'POST', url: './post.php', data: str, callback: print, }) } function news(data){ var newsList = document.getElementById('newsList'); var str = ''; data.forEach(function(ele, index){ str += '<li>'+ele.title+'</li>' ; }); newsList.innerHTML = str; } function print(data){ alert(data) }
post.php文件 后端 代码
<?php header('content-type:text/html;charset="utf-8"'); error_reporting(0); $username = $_POST['username']; $age = $_POST['age']; echo "名字: {$username}, 年龄: {$age}";
getNews.php文件 后端代码
<?php header('content-type:text/html;charset="utf-8"'); error_reporting(0); $news = array( array('title'=>'德国女总理默克尔滑雪时摔倒 骨盆断裂','date'=>'2014-1-6'), array('title'=>'中日驻英外交官撰文互称对方国家为"伏地魔"','date'=>'2014-1-6'), array('title'=>'安倍:望与中国领导人会面 中方:你关闭了大门','date'=>'2014-1-6'), array('title'=>'揭秘台湾驻港间谍网运作 湖北宜昌副市长被查','date'=>'2014-1-6'), array('title'=>'总书记:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'), array('title'=>'总书记:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'), array('title'=>'总书记:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'), array('title'=>'总书记:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'), array('title'=>'总书记:嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'), array('title'=>'中国长达13年游戏机禁令正式解除 外企可进入','date'=>'2014-1-6'), array('title'=>'70种证件伴中国人一生:领养老金要办生存证明','date'=>'2014-1-6'), array('title'=>'德国女总理默克尔滑雪时摔倒 骨盆断裂','date'=>'2014-1-6'), array('title'=>'中日驻英外交官撰文互称对方国家为"伏地魔"','date'=>'2014-1-6'), array('title'=>'安倍:望与中国领导人会面 中方:你关闭了大门','date'=>'2014-1-6'), array('title'=>'揭秘台湾驻港间谍网运作 湖北宜昌副市长被查','date'=>'2014-1-6'), ); echo json_encode($news);