简体   繁体   中英

How to insert HTML form input into API object array

I have two code "snippets" that I would like to combine but I don't really know how to.

I've managed to make HTML form input into an JSON object. See codepen here .

When I click the "Add note" btn I want to grab the input values -> make them to an object -> POST them to my api object array. Image and code example below:

HTML to JSON 在此处输入图片说明

// CREATE NEW NOTES
var btn = document.getElementById('btn');

btn.addEventListener("click", function() {

var request = new XMLHttpRequest();

request.open('POST', 'https://timesheet-1172.appspot.com/af25fa69/notes');

request.setRequestHeader('Content-Type', 'application/json');

request.onload = function () {

    // When I click the "Add note" btn I want to grab the input values -> make them to an object -> POST them to my api object array.

    // Like

    // var body = {
    //  'title': form.title.value,
    //  'description': form.description.value
    // }

};

request.send(JSON.stringify(body));

});

This is the current code that I have which let's me send an already set variable with object properties. See image below:

SEND JSON 在此处输入图片说明

However my question is regarding how i can combine these tho examples so I can make dynamic inputs -> convert them to a JSON object -> Insert them in the api object array.

Feel free to correct me if you think that i'm on the wrong path or if you think have a solution!

If you have any questions or need clarification don't hesitate to ask!

Thanks beforehand!

// E

You could combine them like this (and I think this is the best approach):

Define a function that will be executed on form submit, it will create JSON and send it via ajax:

function formatJSONAndSend(form) {
  var body = {
    title: form.title.value,
    description: form.description.value
  };

  var request = new XMLHttpRequest();
  request.open('POST', 'https://timesheet-1172.appspot.com/af25fa69/notes');
  request.setRequestHeader('Content-Type', 'application/json');    
  request.send(JSON.stringify(body));
}

And you can call it from your HTML like:

<form onsubmit="formatJSONAndSend(this);">
    Title: <input type="text" class="form-control" name="title" placeholder="Title goes here..." /><br /> Description: <input type="text" class="form-control" name="description" placeholder="Description goes here..." /><br />
    <input class="btn btn-primary" id="btn" type="submit" value="Add note">
</form>

After you submit your form by clicking on Add note button it will call the formatJSONAndSend() function which will first grab the data from the form and put it in body object which is then sent via POST to your web api.

Here's a working example: Codepen

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