首先使用express 搭建一個服務器:
const express = require("express"); const app = express(); app.get('/server',function(req,resp){ //設置響應頭 resp.setHeader("Access-Control-Allow-Origin","*"); resp.send("hello,Ajax"); }) app.listen(3000,function(){ console.log("服務器已啟動,3000端口監聽中...") })
HTML頁面如下:Ajax將服務器發出的內容響應給了瀏覽器頁面id為result的div元素。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ajax Document</title> <style> #result{ width:200px; height:100px; border:solid 1px #90b; } </style> </head> <body> <button>點擊發送請求</button> <div id="result"></div> <script> const btn = document.getElementsByTagName("button")[0]; var result = document.getElementById("result"); btn.onclick = function(){ //1.創建對象 const xhr = new XMLHttpRequest() //2.初始化,設置請求方法和url xhr.open('GET','http://localhost:3000/server',) //3.發送 xhr.send(); //4.事件綁定 處理服務端返回的結果 //readystate 是 xhr對象中的屬性,表示狀態:0,1,2,3,4 xhr.onreadystatechange = function(){ // 判斷 if(xhr.readyState == 4){ //判斷響應狀態碼 200 404 403 401 500 if(xhr.status >=200 && xhr.status < 300){ // //處理結果 行 頭 空行 體 // console.log(xhr.status); // console.log(xhr.statusText); // console.log(xhr.getAllResponseHeader); // console.log(xhr.response); //響應 result.innerHTML =xhr.response; } } } } </script> </body> </html>
moseover響應ajax請求
服務器設置發送信息:
const express = require("express"); const app = express(); app.get('/server',function(req,resp){ //設置響應頭 resp.setHeader("Access-Control-Allow-Origin","*"); resp.send("hello,Ajax"); }) app.listen(3000,function(){ console.log("服務器已啟動,3000端口監聽中...") }) app.post('/server',function(req,resp){ //設置響應頭 resp.setHeader("Access-Control-Allow-Origin","*"); resp.send("hello,Ajax from post"); })
html及js相關代碼:
<body> <button>點擊發送請求</button> <div id="result"></div> <script> const btn = document.getElementsByTagName("button")[0]; var result = document.getElementById("result"); btn.onclick = function(){ //1.創建對象 const xhr = new XMLHttpRequest() //2.初始化,設置請求方法和url xhr.open('GET','http://localhost:3000/server?a=100&b=200&c=300') //設置請求頭 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") //3.發送 // xhr.send('a=100&b=200&c=300'); xhr.send('a:100,b:200,c;300') //4.事件綁定 處理服務端返回的結果 //readystate 是 xhr對象中的屬性,表示狀態:0,1,2,3,4 xhr.onreadystatechange = function(){ // 判斷 if(xhr.readyState == 4){ //判斷響應狀態碼 200 404 403 401 500 if(xhr.status >=200 && xhr.status < 300){ // //處理結果 行 頭 空行 體 // console.log(xhr.status); // console.log(xhr.statusText); // console.log(xhr.getAllResponseHeader); // console.log(xhr.response); //響應 result.innerHTML =xhr.response; } } } } </script> </body>
keydown響應ajax請求並使用json傳輸數據
設置服務器和需要傳輸的數據:
app.all('/json-server',function(req,resp){ //設置響應頭 resp.setHeader("Access-Control-Allow-Origin","*"); const data ={'name':'atguigu'}; let str = JSON.stringify(data); resp.send(str); })
html和js代碼如下:
<body> <div id="result"></div> <script> const result = document.getElementById("result"); window.onkeydown =function(){ const xhr = new XMLHttpRequest(); //設置響應體數據類型 xhr.responseType="json"; xhr.open('GET','http://localhost:3000/json-server'); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status >= 200 && xhr.status < 300){ //手動對數據轉換 // let data = JSON.parse(xhr.response); // console.log(data); // result.innerHTML=data.name; //自動轉換(通過設置xml數據響應格式) result.innerHTML= xhr.response.name; } } } } </script> </body>
解決IE瀏覽器緩存問題,加上當前實時日期
xhr.open('GET','http://localhost:3000/ie-server?t='+Date.now());
超時及網絡異常的Ajax處理:
<body> <button>點擊發送請求</button> <div id="result"></div> <script> const btn = document.getElementsByTagName("button")[0]; const result = document.querySelector("#result"); btn.addEventListener('click',function(){ //1.創建對象 const xhr = new XMLHttpRequest(); //超時設置2s xhr.timeout=2000; //超時回調 xhr.ontimeout=function(){ alert("網絡異常,請稍后嘗試") } //網絡異常回調 xhr.onerror = function(){ alert("你的網絡似乎出了一些問題") } //2.初始化,設置響應類型和url,解決IE瀏覽器緩存問題,加上當前實時日期 xhr.open('GET','http://localhost:3000/delay'); //3.發送 xhr.send(); //4.時間綁定 xhr.onreadystatechange=function(){ if(xhr.readyState == 4){ if(xhr.status >=200 && xhr.status < 300){ result.innerHTML = xhr.response; } } } }) </script> </body>
調用abort方法取消ajax請求:
<body> <button>發送請求</button> <button>取消請求</button> <script> const btns = document.querySelectorAll("button"); let xhr = null; //單擊事件獲取ajax請求 btns[0].onclick = function(){ xhr = new XMLHttpRequest(); xhr.open('GET','http://localhost:3000/delay'); xhr.send(); } //調用abort方法取消ajax請求 btns[1].onclick = function(){ xhr.abort(); } </script> </body>
ajax處理重復請求:
<body> <button>發送請求</button> <script> const btns = document.querySelectorAll("button"); let xhr = null; //標識變量 let isSending = false;//是否正在發送AJAX請求 //單擊事件獲取ajax請求 btns[0].onclick = function(){ //判斷標識變量,如果標識變量為false,則取消當前請求,創建一個新的請求 if(isSending) xhr.abort(); xhr = new XMLHttpRequest(); //修改變量標識 isSending = true; xhr.open('GET','http://localhost:3000/delay'); xhr.send(); xhr.onreadystatechange =function(){ if(xhr.readyState === 4){ isSending = false; } } } </script> </body>
Jquery中的Ajax請求:
<body> <div class="container"> <h2 class="page-header">Jquery 發送Ajax請求</h2> <button class="btn btn-primary">GET</button> <button class="btn btn-danger">POST</button> <button class="btn btn-info">通用型方法</button> </div> <script> $("button").eq(0).click(function(){ $.get('http://localhost:3000/jquery-server',{a:100,b:100},function(data){ console.log(data); },'json'); }) $("button").eq(1).click(function(){ $.get('http://localhost:3000/jquery-server',{a:100,b:100},function(data){ console.log(data); }); }) $("button").eq(2).click(function(){ $.ajax({ //url url:'http://localhost:3000/jquery-server', //參數 data:{a:100,b:200}, //請求類型 type:'GET', //響應體結果 dataType:'json', //成功的回調 success: function(data){ console.log(data); }, //超時時間 timeout:2000, //失敗的回調 error:function(){ console.log("出錯啦"); }, //頭信息(可選) headers:{ c:300, d:400 }, }) }) </script> </body>