如何在Jquery Ajax中向请求添加标头? [英] How to add header to request in Jquery Ajax?

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

问题描述

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

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

下面是代码:-

$.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);
    }
});

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

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

然后,我使用了请求(请求是chrome + firefox插件我们可以通过它手动将标头添加到请求中).

手动添加标题后:-

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

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.

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

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

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

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' }
});

如果要向每个请求添加默认标头(或标头集),请使用$.ajaxSetup():,这将帮助您添加标头.

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' });

向每个请求添加标头(或标头集),然后将$ S.ajaxSetup()与beforeSend挂钩一起使用:

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' });

参考链接:AjaxSetup

参考链接:AjaxHeaders

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆