在 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 请求。查看输出:

在 jQuery 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 数据。见输出:

在 jQuery AJAX 中传递请求标头