使用 XMLHttpRequest 對象能夠和服務器進行交互,能夠獲取到數據,而無需讓整個頁面進行刷新.這樣 web 頁面能夠作到只更新局部頁面,下降了對用戶操做的影響.html
XMLHttpRequest 對象能夠用於獲取各類類型的數據,而不止是 xml,還支持 JSON,HTML 或者純文本node
let http = require("http"); let url = require("url"); const port = 3333; http.createServer((request, response) => { response.setHeader("Access-Control-Allow-Origin", "*"); response.writeHead(200, { "Content-type": "text/html;charset=utf8" }); if (request.url !== "/favicon.ico") { let pathname = url.parse(request.url).pathname; pathname = pathname.replace(/\//, ""); if (pathname === "get_money") { get_money(request, response); } response.end("\r\n錢給完了,沒了", "utf-8"); } }).listen(port); console.log(`本地服務器建立成功=>localhost:${port}`); function get_money(request, response) { response.write("給了你666塊錢", "utf-8"); }
安裝個 node,跑在本地就行web
var xhr = new XMLHttpRequest(); console.log("open調用前的status", xhr.status); // open調用前的status 0 console.log("open調用前的readyState", xhr.readyState); //open調用前的readyState 0 xhr.open("GET", "http://127.0.0.1:3333/get_money", true); console.log("open調用後的status", xhr.status); //open調用後的status 0 console.log("open調用後的readyState", xhr.readyState); //open調用後的readyState 1 xhr.send(); console.log("send調用後的status", xhr.status); //send調用後的status 0 console.log("send調用後的readyState", xhr.readyState); //send調用後的readyState 1 xhr.onreadystatechange = function() { console.log(xhr.status); //2,3,4 console.log(xhr.readyState); //200,200,200 if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { } };
readyState 表明 send()方法已經被調用,可是 send()以後 readyState 不必定就是 2json
當服務器指定了 status,其實就是 http 的狀態碼跨域
//node中writeHead修改一下 response.writeHead(404, { "Content-type": "text/html;charset=utf8" });
var xhr = new XMLHttpRequest(); xhr.open("GET", "http://127.0.0.1:3333/get_money", true); xhr.onreadystatechange = function() { console.log("readyState=>", xhr.readyState); console.log("status=>", xhr.status); console.log(xhr.response); console.log(xhr.responseText); }; xhr.send();
一個小案例瀏覽器
經過請求發送一個留言,經過 FormData 發送一個表單數據安全
var xhr = new XMLHttpRequest(); xhr.open("POST", "http://127.0.0.1:3333/add", true); var body = new FormData(); body.append("oid", 8029794); body.append("type", 1); body.append("message", "本大王來巡山了"); body.append("plat", 1); body.append("jsonp", "jsonp"); body.append("csrf", "af15b2a3a0e64a2ea304f885bea6bfd1"); xhr.send(body); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.response); } };
爲了安全,跨域 XHR 對象有一些限制:服務器
FormDatacookie