Ajax--向服務器端發送請求、接收服務器響應數據


Ajax的實現步驟
1、創建Ajax對象
var xhr=new XMLHttpRequest();

2、告訴Ajax請求地址及請求方式
xhr.open('get','http://www.example.com');

3、發送請求
xhr.send();

4、獲取服務器端給予客戶端的響應數據
xhr.onload=function(){
console.log(xhr.responseText);
}

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="utf-8"> 
 5     <title>Document</title>
 6 </head>
 7 <body>
 8     <script type="text/javascript">
 9         var xhr=new XMLHttpRequest();
10         xhr.open('get','http://localhost:3000/first');
11         xhr.send();
12         xhr.onload=function(){
13             console.log(xhr.responseText)
14         }
15     </script>
16 </body>
17 </html>

app.js

 1 //引入express框架
 2 const express=require('express')
 3 
 4 //引入路徑處理模塊
 5 const path=require('path')
 6 
 7 //創建web服務器
 8 const app=express();
 9 
10 //靜態資源訪問服務器功能
11 app.use(express.static(path.join(__dirname,'public')))
12 
13 app.get('/first',(req,res)=>{
14     res.send('Hello Ajax');
15 })
16 //監聽端口
17 app.listen(3000);
18 
19 //控制台提示輸出
20 console.log('服務器啟動成功1')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM