简体   繁体   English

如何使用 javascript XHR 将表单输入分配给 API 发布请求?

[英]How to assign form inputs to API Post request with javascript XHR?

I am making a post request using XHR javascript as showing below:我正在使用 XHR javascript 发出帖子请求,如下所示:

let postObj = {
"Key": 1167722112,
"Remark": "",
"Total": 2,
"TotalTransferred": 0,
"SODTL": [
  {
    "Dtl": 11678,
    "Code": "Screw Hex",
    "Detail": true,
    "DTL": []
  }
]
}

let post = JSON.stringify(postObj)

const url = "http://example/api/Order/"
let xhr = new XMLHttpRequest()

xhr.open('POST', url, true)
xhr.setRequestHeader("Authorization", "eyJhbGciOiJoAKk8b8ToV7HFcg");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(post);

xhr.onload = function () {
if(xhr.status === 201) {
    console.log("Post successfully created!")
}
}

and the above request is working fine but i want to get the data from form instead of being hard coded并且上面的请求工作正常,但我想从表单中获取数据而不是硬编码

how can i assign each field from the API to specific input?如何将 API 中的每个字段分配给特定输入?

for example:例如:

let postObj = {
"Key": => input name from form
"Remark": input name from form,
"Total": input name from form,
"TotalTransferred": input name from form,
"SODTL": [
  {
    "Dtl": input name from form,
    "Code": input name from form,
    "Detail": input name from form,
    "DTL": []
  }
]
}

and as you can see there is an array inside the call, is it gonna be the same when i assign it to input name?如您所见,调用中有一个数组,当我将其分配给输入名称时,它是否会相同? like name="field name" or name="[]field name"?像 name="field name" 或 name="[]field name"?

Note: English isn't my mother tongue so please do let me know if you need more explanation注意:英语不是我的母语,所以如果您需要更多解释,请告诉我

The solution to assign a specific data from API to a specific input name inside a form将 API 中的特定数据分配给表单内的特定输入名称的解决方案

"Key": $('input[name="Key"]').val(),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM