POST headers 和 body 使用 Jquery AJAX

POST headers and body using Jquery AJAX

我必须向经纪人 API 发送一个 POST,包括 header 和一个 body:

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" 
} 

API 在这里:https://labs.ig.com/rest-trading-api-guide

问题是互联网上的每个示例都将数据作为 "data" 发送,如下所示:

jQuery.ajax(

{

url : 'https://demo-api.ig.com/gateway/deal/session',

type: 'POST',

dataType : "json",

data: {identifier: "A12345", password: "112233"}

});

我不明白,header和body在哪里?所有的例子基本上都是这样的,我无法从中得出结论。

数据是针对您的 post 参数的,headers 有自己的 object。

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"}

});

使用beforeSend回调函数并设置headers。试试下面的代码 -

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');},    
});