HOWTO · jQuery

在 jQuery AJAX 中傳遞請求標頭

本教程演示瞭如何在 jQuery AJAX 中使用標頭。

標頭指定在 jQuery AJAX 中從伺服器接受的響應型別。本教程演示如何在 jQuery AJAX 中使用標頭。

在 jQuery AJAX 中傳遞請求標頭

如上所述,標頭可以指定在 jQuery AJAX 中從伺服器接受的響應型別。標頭是傳遞給 jQuery 中的 ajax() 方法的內建選項。

標頭是使用 XMLHttpRequest 物件在 AJAX 請求中傳送的鍵值對。一個非同步 HTTP 請求和一個標頭將通知伺服器接受什麼樣的響應。

回撥函式也可用於設定標頭屬性。

jQuery AJAX 標頭的語法是:

$.ajax({ headers : { key : value }})

beforeSend 回撥函式覆蓋標頭屬性的語法是:

$.ajax({beforeSend: function (jqXHR, settings) { jqXHR.setRequestHeader(key, value) );}})

headers : { key : value } 是一個可選選項。在向伺服器傳送請求時,它將指定從伺服器接受的響應型別。

headers 的預設值為 {},這是一個普通物件型別。標題的鍵是 AcceptAccept-EncodingAccept-LanguageConnectionCookieUser-AgentHostOrder-Number 等。

beforeSend 是一個可選函式,它將設定或覆蓋以指定從伺服器接受的響應型別。它將接受 jqXHRsettings 引數將修改 jqXHR 物件並使用 setRequestHeader 方法新增自定義標頭。

讓我們嘗試一個使用 AJAX 標頭的簡單示例來從伺服器獲取資料:

<!doctype html>
<html lang = "en">
<head>
    <meta charset = "utf-8">
    <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <title> jQuery Ajax headers </title>
</head>
<body>
    <h3> jQuery ajax headers : </h3>
    <button id = "Send_Request" > Send the ajax request with headers <button/>
    <br>
    <p id = "para1" style = "color : green"> </p>
    <script type = "text/javascript">
    $(document).ready( function () {
        $('#Send_Request').click( function(){
        var Ajax_Request = $.ajax( { url : 'http://localhost/',
            contentType : 'application/json',
            dataType : 'json',
            headers: {"Accepts": "text/plain; charset=utf-8"}
        });
        ajxReq.success( function ( Request_Data, Request_Status, jqXHR ) {
            $( '#para1' ).append( '<h2> The JSON data: </h2>');
            $( '#para1' ).append( '<p> The Request Date : ' + Request_Data.date + '</p>');
            $( '#para1' ).append ('<p> The Request Time: ' + Request_Data.time + '</p>');
            $( '#para1' ).append( '<p> The Request Status : ' + Request_Status + '</p>');
        });
        Ajax_Request.error( function ( jqXHR, Text_Status, Error_Message ) {
            $( "p" ).append( "The status is :" +Text_Status);
        });
        });
    });
    </script>
</body>
</html>

上面的程式碼將嘗試傳送帶有標題選項 "Accepts": "text/plain; charset=utf-8" 的 AJAX 請求。檢視輸出:

AJAX 標頭

如輸出所示,它會丟擲錯誤,因為在標頭中,我們向伺服器請求純文字,但接收到的資料是 JSON,因此會丟擲錯誤。要成功處理請求,我們必須將標頭值設定為 JSON。

讓我們試著糾正這個例子:

<!doctype html>
<html lang = "en">
<head>
    <meta charset = "utf-8">
    <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <title> jQuery Ajax headers </title>
</head>
<body>
    <h3> jQuery ajax headers : </h3>
    <button id = "Send_Request" > Send the ajax request with headers <button/>
    <br>
    <p id = "para1" style = "color : green"> </p>
    <script type = "text/javascript">
    $(document).ready( function () {
        $('#Send_Request').click( function(){
        // url from where we want to get the data
        var ajxReq = $.ajax( { url : 'http://time.jsontest.com',
        contentType : 'application/json',
        dataType : 'json',
        headers: {"Accept": "application/json"}
        });
        ajxReq.success( function ( Request_Data, Request_Status, jqXHR ) {
            $( '#para1' ).append( '<h2> The JSON data: </h2>');
            $( '#para1' ).append( '<p> The Request Date : ' + Request_Data.date + '</p>');
            $( '#para1' ).append ('<p> The Request Time: ' + Request_Data.time + '</p>');
            $( '#para1' ).append( '<p> The Request Status : ' + Request_Status + '</p>');
        });
        ajxReq.error( function ( jqXHR, Text_Status, Error_Message ) {
            $( "p" ).append( "The status is : " + Text_Status);
        });
        });
    });
    </script>
</body>
</html>

上面的程式碼將傳送一個標頭值為 JSON 的 AJAX 請求,程式碼將從伺服器獲取 JSON 資料。見輸出:

AJAX 標頭 JSON