前端學習(1417):ajax實現步驟

ajax.js

// 引用expess框架
const express = require('express');
// 處理路徑
const path = require('path');

// 創建網站服務器
const app = express();
app.get('/first', (req, res) => {
    res.send('hello geyao')
})
app.use(express.static(path.join(__dirname)));
// 監聽端口
app.listen(3000);
console.log('網站服務器啓動成功, 請訪問localhost')

ajax.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8"><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //1創建ajax對象
        var xhr = new XMLHttpRequest();
        //請求方式
        xhr.open('get', 'http://localhost:3000/responsdate');
        //發送請求
        xhr.send();
        //獲取數據
        xhr.onload = function() {
            /* console.log(xhr.responseText); */
            var res = JSON.parse(xhr.responseText);
            console.log(res);
            var str = '<h2></h2>'
            document.body.innerHTML = str;
        }
    </script>
</body>

</html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //1創建ajax對象
        var xhr = new XMLHttpRequest();
        //請求方式
        xhr.open('get', 'http://localhost:3000/first');
        //發送請求
        xhr.send();
        //獲取數據
        xhr.onload = function() {
            console.log(xhr.responseText);
        }
    </script>
</body>

</html>

運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章