全称:Asynchronous JavaScript and XML (异步的JavaScript和XML)
不是某种编程语言,是一种在无需重新加载整个网页的情况下能够更新部分网页的技术,异步更新,局部更新;后台和服务器交换数据,通过XMLHttpRequest对象
流程:运用HTML和CSS实现页面,表达信息;运用XMLHttpRequest和web服务器进行数据的异步交换;运用JavaScript操作DOM,实现动态局部刷新
XMLHttpRequest对象:
var request; if (window.XMLHttpRequest){ request = new XMLHttpRequest();//IE7+,Firefox,Chrome,Opera,Safari..l }else{ request = new ActiveXObject("Microsoft.XMLHttp");//IE6,IE5 }
HTTP:
是计算机通过网络进行通信的规则,是一种无状态(不建立持久的连接,没有记忆)协议
一个完整的HTTP请求,7个步骤:1:建立TCP连接;2:Web浏览器向Web服务器发送请求命令;3.浏览器发送请求头信息;4.服务器应答;5.服务器发送应答头信息;6.服务器向浏览器发送数据;7.服务器关闭TCP连接
一个HTTP请求一般由四部分组成:1.请求的方法或动作(GET还是POST);2.请求的URL(请求的地址);3.请求头,包含一些客户端环境信息,身份证信息等
4.请求体(请求正文),可以包含客户提交的查询字符串信息,表单信息等
GET:一般用于信息获取,使用URL传递参数(发送的信息对任何人都可见,所有的变量名和值都显示在URL中),对所发送信息的数量也有限制,一般在2000字符;幂等(一个GET请求执行一次和一万次的效果是相同的);
POST:一般用于修改服务器上的资源,对所发送信息的数量无限制,更安全
HTTP相应一般由三部分组成:1.一个数字和文字组成的状态码,用来显示请求是否成功;2.响应头,也和请求头一样包含许多有用的信息,例如服务器类型,日期和时间,内容类型和长度等;3.响应体,也就是响应正文
HTTP状态码(request.status):由3位数字构成,其中首位数字定义了状态码的类型
1XX:信息类,表示收到web浏览器请求,正在进一步的处理中
2XX:成功,表示用户请求被正确接收,理解和处理例如:200 OK
3xx:重定向,表示请求没有成功,客户必须采取进一步的动作
4XX:客户端错误,表示客户端提交的请求有错误,例如:404 NOT Found,意味着请求中所引用的文档不存在。
5xx:服务器错误,表示服务器不能完成请求的处理
XMLHttpRequest发送请求:
open(method,url,async)
send(string)
例子:
request.open("GET","get.php",true); request.send(); request.open("POST","post.php",true); request.send(); request.open("POST","create.php",true); request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); request.send("name=王二狗&sex=男");
XMLHttpRequest取得响应:
responseText:获得字符串形式的响应数据
responseXML:获得XML形式的响应数据
status和statusText:以数字和文本形式返回HTTP状态码
getAllResponseHeader():获取所有的响应报头
getResponseHeader():查询响应中的某个字段的值
readyState属性:(通过request.onreadystatechange来监听)
0:请求未初始化,open还没有调用
1:服务器连接已经建立,open已经调用了
2:请求已经接收,也就是接收到头信息了
3:请求处理中,也就是接收到响应主体了
4:请求已完成,且响应已就绪,也就是响应完成了
var request; if (window.XMLHttpRequest){ request = new XMLHttpRequest();//IE7+,Firefox,Chrome,Opera,Safari..l }else{ request = new ActiveXObject("Microsoft.XMLHttp");//IE6,IE5 } request.open("GET","get.php",true); request.send(); request.onreadystatechange = function(){ if (request.readyState === 4 && request.status === 200){ //做一些事情 request.responseText } }
Demo:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Demo</title> 6 <style> 7 #box{ 8 line-height: 1.8; 9 margin: 10px auto; 10 width: 350px; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="box"> 16 <h1>员工查询</h1> 17 <label>请输入员工编号:</label> 18 <input type="text" id="keyword"/> 19 <button id="search">查询</button> 20 <p id="searchResult"></p> 21 22 <h1>员工查询</h1> 23 <label>请输入员工姓名:</label> 24 <input type="text" id="staffName"/><br> 25 <label>请输入员工编号:</label> 26 <input type="text" id="staffNumber"/><br> 27 <label>请输入员工性别:</label> 28 <select name="" id="staffSex"> 29 <option value="">男</option> 30 <option value="">女</option> 31 32 </select><br> 33 <label>请输入员工职位:</label> 34 <input type="text" id="staffJob"/><br> 35 <button id="save">保存</button> 36 <p id="createResult"></p> 37 38 </div> 39 40 <script type="text/javascript"> 41 document.getElementById("search").onclick = function(){ 42 //发送Ajax查询请求处理 43 var request; 44 if (window.XMLHttpRequest){ 45 request = new XMLHttpRequest();//IE7+,Firefox,Chrome,Opera,Safari..l 46 }else{ 47 request = new ActiveXObject("Microsoft.XMLHttp");//IE6,IE5 48 } 49 request.open("GET","service.php?number="+document.getElementById("keyword").value); 50 request.send(); 51 request.onreadystatechange = function(){ 52 if(request.readyState===4){ 53 if(request.status===200){ 54 var data = JSON.parse(request.responseText); 55 if(data.success){ 56 document.getElementById("searchResult").innerHTML=data.msg; 57 }else{ 58 document.getElementById("searchResult").innerHTML="出现错误:" + data.msg; 59 } 60 }else{ 61 alert("发生错误:"+request.status); 62 } 63 } 64 } 65 } 66 67 document.getElementById("save").onclick = function(){ 68 //发送Ajax查询请求处理 69 var request; 70 if (window.XMLHttpRequest){ 71 request = new XMLHttpRequest();//IE7+,Firefox,Chrome,Opera,Safari..l 72 }else{ 73 request = new ActiveXObject("Microsoft.XMLHttp");//IE6,IE5 74 } 75 request.open("POST","service.php"); 76 var data = "name=" +document.getElementById("staffName").value 77 +"&number=" +document.getElementById("staffNumber").value 78 +"&sex=" +document.getElementById("staffSex").value 79 +"&job=" +document.getElementById("staffJob").value; 80 request.serRequestHeader("Content-Type","application/x-www-form-urlencoded"); 81 request.send(data); 82 request.onreadystatechange = function(){ 83 if(request.readyState===4){ 84 if(request.status===200){ 85 var data = JSON.parse(request.responseText); 86 if(data.success){ 87 document.getElementById("creatResult").innerHTML=data.msg; 88 }else{ 89 document.getElementById("creatResult").innerHTML="出现错误:" + data.msg; 90 } 91 }else{ 92 alert("发生错误:"+request.status); 93 } 94 } 95 } 96 } 97 98 99 /*var jsondata = '{"staff":[{"name":"洪七","age":70},{"name":"郭靖","age":35},{"name":"黄蓉","age":30}]}' 100 var jsonobj = eval('('+ jsondata + ')'); 101 alert(jsonobj.staff[0].name); 102 103 var jsondata = '{"staff":[{"name":"洪七","age":70},{"name":"郭靖","age":35},{"name":"黄蓉","age":30}]}' 104 var jsonobj = JSON.parse(jsondata); 105 alert(jsonobj.staff[0].name);*/ 106 107 </script> 108 109 </body> 110 </html>
JSON:JavaScript对象表示法(JavaScript Object Notation);JSON是存储和交换文本信息的语法,类似XML。它采用键值对的方式来组织,易于人们阅读和编写,同时也易于机器解析和生成;JSON是独立于语言的,也就是说不管什么语言,都可以解析JSON,只要按照JSON的规则来就行。
相比XML的有点:JSON的长度更短小,读写速度更快,可以使用JavaScript内建的方法直接进行解析,转换成JavaScript对象,非常方便
JSON数据的书写格式:名称/值对;名称写在前面(在双引号中),值对写在后面(同样的双引号中),中间用冒号隔开 例如:"name":"郭靖"
JSON的值可以是下面这些类型:数字(整数或浮点数);字符串(在双引号中);逻辑值(true或false);数组(在方括号中);对象(在花括号中);null;
JSON例子:
{ "staff":[ {"name":"洪七","age":70}, {"name":"郭靖","age":35}, {"name":"黄蓉","age":30} ] }
JSON解析:eval和JSON.parse
在代码中使用eval是很危险的!特别是用它执行第三方的JSON数据(其中可能包含恶意代码)时,尽可能使用JSON.parse()方法解析字符串本身,该方法还可以捕捉JSON中的语法错误。
var jsondata = '{"staff":[{"name":"洪七","age":70},{"name":"郭靖","age":35},{"name":"黄蓉","age":30}]}' var jsonobj = eval('('+ jsondata + ')'); alert(jsonobj.staff[0].name); var jsondata = '{"staff":[{"name":"洪七","age":70},{"name":"郭靖","age":35},{"name":"黄蓉","age":30}]}' var jsonobj = JSON.parse(jsondata); alert(jsonobj.staff[0].name);
在线的JSON字符串校验:JSONLint.com
使用JSON的Demo:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Demo</title> <style> #box{ line-height: 1.8; margin: 10px auto; width: 350px; } </style> </head> <body> <div id="box"> <h1>员工查询</h1> <label>请输入员工编号:</label> <input type="text" id="keyword"/> <button id="search">查询</button> <p id="searchResult"></p> <h1>员工查询</h1> <label>请输入员工姓名:</label> <input type="text" id="staffName"/><br> <label>请输入员工编号:</label> <input type="text" id="staffNumber"/><br> <label>请输入员工性别:</label> <select name="" id="staffSex"> <option value="">男</option> <option value="">女</option> </select><br> <label>请输入员工职位:</label> <input type="text" id="staffJob"/><br> <button id="save">保存</button> <p id="createResult"></p> </div> <script type="text/javascript"> document.getElementById("search").onclick = function(){ //发送Ajax查询请求处理 var request; if (window.XMLHttpRequest){ request = new XMLHttpRequest();//IE7+,Firefox,Chrome,Opera,Safari..l }else{ request = new ActiveXObject("Microsoft.XMLHttp");//IE6,IE5 } request.open("GET","service.php?number="+document.getElementById("keyword").value); request.send(); request.onreadystatechange = function(){ if(request.readyState===4){ if(request.status===200){ var data = JSON.parse(request.responseText); if(data.success){ document.getElementById("searchResult").innerHTML=data.msg; }else{ document.getElementById("searchResult").innerHTML="出现错误:" + data.msg; } }else{ alert("发生错误:"+request.status); } } } } document.getElementById("save").onclick = function(){ //发送Ajax查询请求处理 var request; if (window.XMLHttpRequest){ request = new XMLHttpRequest();//IE7+,Firefox,Chrome,Opera,Safari..l }else{ request = new ActiveXObject("Microsoft.XMLHttp");//IE6,IE5 } request.open("POST","service.php"); var data = "name=" +document.getElementById("staffName").value +"&number=" +document.getElementById("staffNumber").value +"&sex=" +document.getElementById("staffSex").value +"&job=" +document.getElementById("staffJob").value; request.serRequestHeader("Content-Type","application/x-www-form-urlencoded"); request.send(data); request.onreadystatechange = function(){ if(request.readyState===4){ if(request.status===200){ var data = JSON.parse(request.responseText); if(data.success){ document.getElementById("creatResult").innerHTML=data.msg; }else{ document.getElementById("creatResult").innerHTML="出现错误:" + data.msg; } }else{ alert("发生错误:"+request.status); } } } } /*var jsondata = '{"staff":[{"name":"洪七","age":70},{"name":"郭靖","age":35},{"name":"黄蓉","age":30}]}' var jsonobj = eval('('+ jsondata + ')'); alert(jsonobj.staff[0].name); var jsondata = '{"staff":[{"name":"洪七","age":70},{"name":"郭靖","age":35},{"name":"黄蓉","age":30}]}' var jsonobj = JSON.parse(jsondata); alert(jsonobj.staff[0].name);*/ </script> </body> </html>
用jQuery实现Ajax:
jQuery.ajax([settings])
type:类型,”POST"或“GET”,默认为“GET”
url:发送请求的地址
data:是一个对象,连同请求发送到服务器的数据
dataType:预期服务器返回的数据类型。如果不指定,jQuery将自动根据HTTP包MIME信息来智能判断,一般我们采用json格式,可以设置为“json"
success:是一个方法,请求成功后的回调函数。传入返回后的数据,以及包含成功代码的字符串
error:是一个方法,请求失败时调用此函数。传入XMLHttpRequest对象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Demo</title> 6 <style> 7 #box{ 8 line-height: 1.8; 9 margin: 10px auto; 10 width: 350px; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="box"> 16 <h1>员工查询</h1> 17 <label>请输入员工编号:</label> 18 <input type="text" id="keyword"/> 19 <button id="search">查询</button> 20 <p id="searchResult"></p> 21 22 <h1>员工查询</h1> 23 <label>请输入员工姓名:</label> 24 <input type="text" id="staffName"/><br> 25 <label>请输入员工编号:</label> 26 <input type="text" id="staffNumber"/><br> 27 <label>请输入员工性别:</label> 28 <select name="" id="staffSex"> 29 <option value="">男</option> 30 <option value="">女</option> 31 32 </select><br> 33 <label>请输入员工职位:</label> 34 <input type="text" id="staffJob"/><br> 35 <button id="save">保存</button> 36 <p id="createResult"></p> 37 38 </div> 39 <!-- 引入jquery --> 40 <script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js"></script> 41 <script type="text/javascript"> 42 $(document).ready(function(){ 43 $("#search").click(function(){ 44 $.ajax({ 45 type:"GET", 46 url:"service.php?number="+ $("#keyword").val(), 47 dataType:"json", 48 success:function(data){ 49 if(data.success){ 50 $("#searchResult").html(data.msg); 51 }else{ 52 $("#searchResult").html("出现错误:" + data.msg); 53 } 54 }, 55 error:function(jqXHR){ 56 alert("发生错误:"+jqXHR.status); 57 } 58 }); 59 }); 60 61 $("#save").click(function(){ 62 $.ajax({ 63 type:"POST", 64 url:"service.php", 65 dataType:"json", 66 data:{ 67 name:$("#staffName").val(), 68 number:$("#staffNumber").val(), 69 sex:$("#staffSex").val(), 70 job:$("#staffJob").val(), 71 }, 72 success:function(data){ 73 if(data.success){ 74 $("#createResult").html(data.msg); 75 }else{ 76 $("#createResult").html("出现错误:" + data.msg); 77 } 78 }, 79 error:function(jqXHR){ 80 alert("发生错误:"+jqXHR.status); 81 } 82 }); 83 }); 84 }); 85 86 </script> 87 88 </body> 89 </html>
跨域:
一个域名地址的组成:
http:// www . abc.com : 8080 / script/jquery.js
协议 子域名 主域名 端口号 请求资源地址
当协议、子域名、主域名、端口号中任意一个不相同时,都算作不同域;不同域之间相互请求资源,就算做”跨域“;比如:http://www.abc.com/index.html请求http://www.efg.com/service.php
JS处于安全方面的考虑,不允许跨域调用其他页面的对象。什么是跨域呢,简单地说就是因为JS同源策略的限制,a.com域名下的 js无法操作b.com或是c.a.com域名下的对象。
- 跨域方法一:代理
通过在同域名的web服务器端创建一个代理:
北京服务器(域名:www.beijing.com),上海服务器(域名:www.shanghai.com);
比如在北京的web服务器的后台(www.beijing.com/proxy-shanghaiservice.php)来调用上海服务器(www.shanghai.com/service.php)的服务,然后再把相应结果返回给前端,这样前端调用北京同域名的服务器就和调用上海的服务效果相同了。
- 跨域处理方法二:JSONP
JSONP可用于解决主流浏览器中跨域数据访问的问题。
在www.aaa.com页面中:
<script> function jsonp(json){ alert(json["name"]); } </script> <script src="http://www.bbb.com/jsonp.js"></script>
在www.bbb.com页面中:
jsonp({'name':'洪七','age':24});
需要将原有代码dataType的值从json改为jsonp,再增加一行:
jsonp:"callback"'//任意值
后端要增加
$jsonp = $_GET["callback"];
并且返回值需要用'()'括起来,前面加上$jsonp的值,用逗号连接,例如:
$result=$jsonp.'({"success":false,"msg":"没有找到员工”})';
jsonp只能支持“GET”请求,不支持“POST”请求
- 跨域处理方法三:XHR2
HTML5提供的XMLHttpRequest Level2已经实现了跨域访问以及其他的一些新功能
IE10以下的版本都不支持
在服务器端做一些小小的改动即可: 增加下面两行代码
header("Access-Control-Allow-Origin:*"); header("Access-Control-Allow-Methods:POST,GET");