迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 jQuery AJAX 中传递请求标头

作者:迹忆客 最近更新:2024/03/13 浏览次数:

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

如输出所示,它会抛出错误,因为在标头中,我们向服务器请求纯文本,但接收到的数据是 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 数据。见输出:

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便