如何在 Jquery Ajax 中向请求添加标头?

2023-02-15前端开发问题
38

本文介绍了如何在 Jquery Ajax 中向请求添加标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用 JQuery 在 Ajax 中为请求添加标头.

下面是代码:-

$.ajax({类型:发布",内容类型:应用程序/json",url: "http://localhost:8080/core-service/services/v1.0/patients/registerPatients",数据:JSON.stringify(耐心DTO),//跨域:真,数据类型:'json',标头:{X-AUTH-TOKEN":tokken},成功:功能(耐心DTO){console.log("成功:", PatientDTO);/* location.href = "fieldagentHRA.html";*/如果(类型(存储)!==未定义"){localStorage.setItem("patUrn", patientDTO.data);location.href="fieldagentHRA.html";}},错误:函数(e){console.log("错误:", e);显示(e);},完成:函数(e){启用注册按钮(真);}});

我用 chrome 检查了这个,发现没有添加标题的正文.

然后我用

在两张图片中,请求标头 x-auth-token 都存在于ACCESS-CONTROL-REQUEST-HEADERS"中,但X-AUTH-TOKEN"标头以及标头值存在于第二张图片中,而第二张图片中不存在第一张照片.

所以我的问题是如何使用 JQuery 在 Ajax 中添加请求标头?

解决方案

有几个解决方案取决于你想做什么

<块引用>

如果想为单个请求添加自定义标头(或一组标头),只需添加 headers 属性,这将帮助您发送带有标头的请求.

//带有自定义标头的请求$.ajax({网址:'foo/bar',标题:{'x-my-custom-header':'一些值'}});

<块引用>

如果想为每个请求添加一个默认标头(或一组标头),请使用 $.ajaxSetup(): 这将帮助您添加标头.

//在此处设置标头,然后调用 ajax$.ajaxSetup({标题:{'x-my-custom-header':'一些值'}});//发送你的ajax$.ajax({ url: 'foo/bar' });

<块引用>

为每个请求添加一个标头(或一组标头),然后将 beforeSend 钩子与 $.ajaxSetup() 一起使用:

//在此处挂上您的标头并使用发送前功能进行设置.$.ajaxSetup({发送前:函数(xhr){xhr.setRequestHeader('x-my-custom-header', '一些值');}});//发送你的ajax$.ajax({ url: 'foo/bar' });

<块引用>

参考链接:AjaxSetup

参考链接:AjaxHeaders

I'm trying to add header to request in Ajax with JQuery.

Below is the code :-

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "http://localhost:8080/core-service/services/v1.0/patients/registerPatients",
    data: JSON.stringify(patientDTO),
    //crossDomain : true,
    dataType: 'json',
    headers: {"X-AUTH-TOKEN" : tokken},
    success: function(patientDTO) {
        console.log("SUCCESS: ", patientDTO);
        /* location.href = "fieldagentHRA.html";*/
        if (typeof(Storage) !== "undefined") {
            localStorage.setItem("patUrn", patientDTO.data);
            location.href="fieldagentHRA.html";
        }
    },
    error: function(e) {
    console.log("ERROR: ", e);
    display(e);
    },
    done: function(e) {
    enableRegisterButton(true);
    }
});

I inspected this with chrome and found that header's body is not being added.

Then I used Requestly (Requestly is chrome+firefox plugin with which we can manually add a header to the request).

After manually adding header :-

In both the pics request header x-auth-token is present in "ACCESS-CONTROL-REQUEST-HEADERS" but "X-AUTH-TOKEN" header along with header value is present in second pic which is not there in the first pic.

So my question is how to add request headers in Ajax with JQuery ?

解决方案

There are couple of solutions depending on what you want to do

If want to add a custom header (or set of headers) to an individual request then just add the headers property and this will help you to send your request with headers.

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});

If want to add a default header (or set of headers) to every request then use $.ajaxSetup(): this will help you to add headers.

//Setup headers here and than call ajax
$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your ajax
$.ajax({ url: 'foo/bar' });

add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

//Hook your headers here and set it with before send function.
$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your ajax
$.ajax({ url: 'foo/bar' });

Reference Link : AjaxSetup

Reference Link : AjaxHeaders

这篇关于如何在 Jquery Ajax 中向请求添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125

Rails 3.1 ajax:成功处理
Rails 3.1 ajax:success handling(Rails 3.1 ajax:成功处理)...
2024-04-20 前端开发问题
11

ExecJS::ProgramError: SyntaxError: 保留字“function"
ExecJS::ProgramError: SyntaxError: Reserved word quot;functionquot;(ExecJS::ProgramError: SyntaxError: 保留字“function)...
2024-04-20 前端开发问题
13