jquery ajax怎么通过header传递参数? 不想通过url传参!

jquery ajax header传参
关注者
49
被浏览
67,673

4 个回答

送分题!

首先的首先,涉及业务逻辑的输入是需要通过参数传递的,主要有三种方法:path, query, POST/PUT body

path: GET /api/user/123 其中的123通过path传递

query: GET /api/search_user?userId=123

body: POST /api/user-signup {username: 'john'}

不建议通过header传参的原因:

1. proxy 和 reverse proxy会drop header

2. 不利于传输object

3.

HTTP access control (CORS)

API 一般会设置Access-Control-Allow-Headers,分分钟教你做人。

4. 不利于dev和debug

5. Header长度限制

然后,如果你需要传header,比如Authorization,如下。

jQuery.ajax()

headers (default: {})

Type:

PlainObject

An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added:

1.5

)

$.ajax({
  url: '/path/to/service',
  method: 'GET | POST | PUT | DELETE',
  headers: {
    'Authorization': 'Bearer <jwt token>',