動態

詳情 返回 返回

前端發起網絡請求的幾種常見方式(XMLHttpRequest、FetchApi、jQueryAjax、Axios) - 動態 詳情

摘要

前端發起網絡請求的幾種常見方式包括:

XMLHttpRequest (XHR): 這是最傳統和最常見的方式之一。它允許客户端與服務器進行異步通信。XHR API 提供了一個在後台發送 HTTP 請求和接收響應的機制,使得頁面能夠在不刷新的情況下更新部分內容。

Fetch API: Fetch API 是一種新的 Web API,提供了一種更強大、更靈活的方式來發起網絡請求。它使用 Promise對象,簡化了對網絡請求的處理,並且提供了更友好的 API

jQuery Ajax: jQuery 是一個流行的 JavaScript 庫,其中包含了簡化 Ajax 調用的方法。通過 jQueryAjax 方法,可以方便地發送各種類型的 HTTP 請求,並處理響應。

Axios: Axios 是一個基於 PromiseHTTP 客户端,用於瀏覽器和 Node.js 環境。它提供了更簡單的 API,並支持在瀏覽器中使用XMLHttpRequest 或在 Node.js 中使用 http 模塊。在一些大型框架中會被使用,例如Vue.js

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0,viewport-fit=cover">
    <title>前端請求服務器的幾種方式</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.min.js"></script>
    <style>
        h2 {
            text-align: center;
        }
        #app {
            width: 500px;
            margin: 30px auto;
        }
        #ret {
            width: 500px;
            height: 100px;
            background: #272822;
            color: #fff;
            padding: 10px;
            font-size: 14px;
        }
        button {
            padding: 10px 15px;
            background: #39f;
            border: none;
            color: #fff;
            cursor: pointer;
        }
    </style>
</head>
<body>
    
    <h2>前端請求服務器的幾種方式</h2>
    <div id="app">

        <!--XMLHttpRequest-->
        <button onclick="XHR()">XMLHttpRequest</button>
        
        <!--FetchApi-->
        <button onclick="FetchApi()">FetchApi</button>
        
        <!--jQueryAjax-->
        <button onclick="jQueryAjax()">jQueryAjax</button>
        
        <!--Axios-->
        <button onclick="Axios()">Axios</button>
        
        <!--請求結果-->
        <p id="ret"></p>
    
    </div>
    
    <script>
        
        // XMLHttpRequest
        function XHR() {
            
            document.querySelector('#ret').innerHTML = 'XMLHttpRequest請求中...';
            
            // 創建 XMLHttpRequest 對象
            var xhr = new XMLHttpRequest();
            
            // 指定請求的方法和 URL
            xhr.open('GET', './getData.php?type=XMLHttpRequest', true); // true 表示異步請求
            
            // 註冊事件處理程序,以便在請求的不同階段獲取相應的響應
            xhr.onreadystatechange = function() {
                
                if (xhr.readyState === XMLHttpRequest.DONE) { // 請求完成
                
                    if (xhr.status === 200) {
                        
                        // 請求成功
                        console.log(JSON.parse(xhr.responseText)); // 輸出響應數據
                        document.querySelector('#ret').innerHTML = xhr.responseText;
                    } else {
                        console.error('請求失敗: ' + xhr.status); // 輸出錯誤信息
                        document.querySelector('#ret').innerHTML = '請求失敗';
                    }
                }
            };
            
            // 發送請求
            xhr.send();
        }
        
        // FetchApi
        function FetchApi() {
            
            document.querySelector('#ret').innerHTML = 'FetchApi請求中...';
            
            // 使用 fetch() 函數創建一個請求對象
            fetch('./getData.php?type=FetchApi')
            .then(function(response) {
                
                // 檢查響應是否成功
                if (!response.ok) {
                    throw new Error('請求失敗: ' + response.status);
                }
                // 解析響應數據為 JSON 格式並返回
                return response.json();
            })
            .then(function(data) {
                
                // 處理響應數據
                console.log(data);
                document.querySelector('#ret').innerHTML = JSON.stringify(data);
            })
            .catch(function(error) {
                
                // 處理錯誤
                console.error('發生錯誤: ', error);
                document.querySelector('#ret').innerHTML = JSON.stringify(error);
            });
        }
        
        // jQuery Ajax
        function jQueryAjax() {
            
            $.ajax({
                url: './getData.php?type=jQueryAjax',
                method: 'GET',
                dataType: 'json', // 響應數據類型
                beforeSend: function(xhr) {
                    
                    // 在發送請求之前執行的操作,比如設置請求頭
                    $('#ret').html('jQueryAjax請求中...')
                },
                success: function(response) {
                    
                    // 輸出響應數據
                    console.log(response);
                    $('#ret').html(JSON.stringify(response))
                },
                error: function(xhr, status, error) {
                    
                    // 輸出錯誤信息
                    console.error('請求失敗: ' + status); 
                    $('#ret').html('請求失敗')
                }
            });
        }
        
        // Axios
        function Axios() {
            
            document.querySelector('#ret').innerHTML = 'Axios請求中...';
            
            axios.get('./getData.php?type=Axios')
            .then(function(response) {
                
                // 輸出響應數據
                console.log(response.data);
                document.querySelector('#ret').innerHTML = JSON.stringify(response.data);
            })
            .catch(function(error) {
                
                // 輸出錯誤信息
                console.error('請求失敗:', error);
                document.querySelector('#ret').innerHTML = JSON.stringify(error);
            });
        }

    </script>
</body>
</html>

getData.php

<?php
    
    header("Content-type:application/json");
    sleep(1);
    echo json_encode(array('code' => 0,'msg' => $_GET['type'] . '請求成功'), JSON_UNESCAPED_UNICODE);

?>

演示

https://demo.likeyunba.com/web_http/

image.png

作者

TANKING

user avatar Dream-new 頭像 woniuseo 頭像 imba97 頭像 kohler21 頭像 DingyLand 頭像 kongsq 頭像 huangmingji 頭像 Asp1rant 頭像 dalideshoushudao 頭像 aitibao_shichangyingxiao 頭像 cynthia_59675eba1a2ee 頭像 hu_qi 頭像
點贊 39 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.