简体   繁体   中英

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

I am making a post request using XHR javascript as showing below:

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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