blob: 5a1c2988e69de9f707a7f2e35372178f4da8211e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
---
title: XMLHttpRequest.setRequestHeader()
slug: Web/API/XMLHttpRequest/setRequestHeader
tags:
- Reference
- XMLHttpRequests
translation_of: Web/API/XMLHttpRequest/setRequestHeader
---
<p>{{APIRef('XMLHttpRequest')}}</p>
<p><strong>XMLHttpRequest.setRequestHeader()</strong> 是设置HTTP请求头部的方法。此方法必须在 {{domxref("XMLHttpRequest.open", "open()")}} 方法和 {{domxref("XMLHttpRequest.send", "send()")}} 之间调用。如果多次对同一个请求头赋值,只会生成一个合并了多个值的请求头。</p>
<p>如果没有设置 {{HTTPHeader("Accept")}} 属性,则此发送出{{domxref("XMLHttpRequest.send", "send()")}} 的值为此属性的默认值<code>*/*</code> 。</p>
<p>安全起见,有些请求头的值只能由user agent设置:{{Glossary("Forbidden_header_name", "forbidden header names", 1)}}和{{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.</p>
<div class="note">
<p>自定义一些header属性进行跨域请求时,可能会遇到"<strong>not allowed by Access-Control-Allow-Headers in preflight response</strong>",你可能需要在你的服务端设置"Access-Control-Allow-Headers"。</p>
</div>
<h2 id="语法">语法</h2>
<pre class="syntaxbox">myReq.setRequestHeader(<var>header</var>, <var>value</var>);
</pre>
<h3 id="参数">参数</h3>
<dl>
<dt><code>header</code></dt>
<dd>属性的名称。</dd>
<dt><code>value</code></dt>
<dd>属性的值。</dd>
</dl>
<h2 id="说明">说明</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('XMLHttpRequest', '#the-setRequestHeader()-method', 'setRequestHeader()')}}</td>
<td>{{Spec2('XMLHttpRequest')}}</td>
<td>WHATWG living standard</td>
</tr>
</tbody>
</table>
<h2 id="兼容性">兼容性</h2>
{{Compat("api.XMLHttpRequest.setRequestHeader")}}
<h2 id="参考">参考</h2>
<p><a href="/zh-CN/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">使用XMLHttpRequest</a></p>
|