如何添加到Ajax请求自定义HTTP标头JS或jQuery的? [英] How can I add a custom HTTP header to ajax request with js or jQuery?

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

问题描述

有谁知道如何添加或使用JavaScript或者jQuery的创建自定义HTTP标头?

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

推荐答案

有这取决于你所需要的多种解决方案...

There are several solutions depending on what you need...

如果你想为自定义标题(或套头)添加到一个单独的请求,然后只需添加标题属性:

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

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

如果你想添加默认的头(或套头)的每一个请求,然后使用 $ ajaxSetup()

$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

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

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

如果你想为添加页眉(或套头)的每一个请求,然后使用 beforeSend 挂钩与 $ ajaxSetup()

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

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

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

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

修改(详细信息):有一点需要注意的是,与 ajaxSetup 只能定义一组默认的头和你只能定义一个 beforeSend 。如果你调用 ajaxSetup 多次,只有最后一组头将被发送,只有最后一次才-发送回调将执行。

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.

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

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