jquery ajax怎么通过header传递参数?
发布网友
发布时间:2022-04-22 15:34
我来回答
共1个回答
热心网友
时间:2023-11-10 23:32
1、首先 ,涉及业务逻辑的输入是需要通过参数传递的,主要有三种方法: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'}
2、不建议通过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>',
'some-other-header': 'some value'
}
})
.done(function(data){...})
.fail(function(jqXHR){...})
.always(function(){...})