json
你可使用AJAX最主要的两个特性作下列事:跨域
在不从新加载页面的状况下发送请求给服务器。浏览器
接受并使用从服务器发来的数据。安全
var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); // ie7+等现代浏览器 } else if (window.ActiveXObject) { // ie6,老版Opera xhr = new ActiveXObject('Microsft.XMLHTTP'); } xhr.open('get', 'db.json', true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { /* readyState 请求的当前状态 status 响应码 */ xhr.responseText; JSON.parse(xhr.responseText); } } xhr.send();
var xhr = null; // 建立异步对象 if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); // ie7+等现代浏览器 } else if (window.ActiveXObject) { // ie6,老版Opera xhr = new ActiveXObject('Microsft.XMLHTTP'); }
服务器
xhr.open('GET', 'db.json', true);
open()
方法是会有 “权限被拒绝” 错误提示。一个容易犯的错误是你企图经过 domain.tld
访问网站, 而不是使用 www.domain.tld
。若是你真的须要向另外一个域名发送请求, 能够查看 HTTP access control。true
(默认设置),JavaScript执行会持续,而且在服务器尚未响应的状况下与页面进行交互。app
dom
请求报文中请求头的Content-Type应该跟随请求体格式的变化而变化异步
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); httpRequest.send('key1=value1&key2=value2'); xhr.setRequestHeader('Content-Type', 'application/json'); httpRequest.send('{"foo":"123"}');
函数
网站
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on" //或者其余格式, 相似 multipart/form-data,JSON,XML等。
xhr.onreadystatechange = function () { // 若为同步,此代码不用写,直接在send后,用`xhr.responseText`便可。 if (xhr.readyState == 4 && xhr.status == 200) { //在检查完请求状态和HTTP响应码后, 你就能够用服务器返回的数据作任何你想作的了 xhr.responseText; JSON.parse(xhr.responseText); } }
|
名 |
解释 |
---|---|---|
0:未初始化 |
UNSENT |
还没有调用open()方法 |
1:启动 |
OPENED |
已经调用open()方法,已创建服务器链接,但还没有调用send()方法 |
2:发送 |
HEADERS_RESPONSE |
已经调用send()方法,请求已接受,但还没有接受到响应拿不到响应体(responseText),此时能够拿到头.getAllResponseHeaders() |
3:接收 |
LOADING |
已经接收到部分响应数据 |
4:完成 |
DONE |
已经接收到所有响应数据,并且能够在客户端使用 |
服务器以文本字符的形式返回
以 XMLDocument 对象方式返回,以后就可使用JavaScript来处理
跨域问题 HTTP access control
HTTP全部响应码 MDN