javascript 使用 Jquery AJAX POST 标头和正文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32412672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
POST headers and body using Jquery AJAX
提问by Youss
I have to send a POST to a broker API including headers and a body:
我必须将 POST 发送到代理 API,包括标题和正文:
Action POST https://demo-api.ig.com/gateway/deal/session
Header
Content-Type: application/json; charset=UTF-8
Accept: application/json; charset=UTF-8
X-IG-API-KEY: 5FA056D2706634F2B7C6FC66FE17517B
Body
{
"identifier": "A12345",
"password": "112233"
}
The API is here: https://labs.ig.com/rest-trading-api-guide
API 在这里:https: //labs.ig.com/rest-trading-api-guide
The problem is that every example on the internet sends the data as "data" like this:
问题是互联网上的每个示例都将数据作为“数据”发送,如下所示:
jQuery.ajax(
{
url : 'https://demo-api.ig.com/gateway/deal/session',
type: 'POST',
dataType : "json",
data: {identifier: "A12345", password: "112233"}
});
I don't understand this, where is the header and the body? All examples look basically like this, I can't make heads or tail out of this.
我不明白这个,标题和正文在哪里?所有的例子看起来基本上都是这样,我无法从中做出正面或反面。
采纳答案by Vishnu Atrai
Using beforeSend
call back function and set headers. try below code -
使用beforeSend
回调函数并设置标题。试试下面的代码 -
jQuery.ajax({
url : 'https://demo-api.ig.com/gateway/deal/session',
type: 'POST',
dataType : "json",
data: {identifier: "A12345", password: "112233"}
beforeSend: function(xhr){xhr.setRequestHeader('X-Header', 'header-value');},
});
回答by Saar
The data is for the post parameters in your case, headers have their own object.
数据用于您的情况下的 post 参数,标题有自己的对象。
jQuery.ajax(
{
url : 'https://demo-api.ig.com/gateway/deal/session',
type: 'POST',
dataType : "json",
headers: {"X-IG-API-KEY":"5FA056D2706634F2B7C6FC66FE17517B"},
data: {identifier: "A12345", password: "112233"}
});