B
B
bpGusar2018-05-07 22:37:24
JavaScript
bpGusar, 2018-05-07 22:37:24

How to send data to server from form as json?

There is React and there is a backing in Java, how to send data from the form to the back as json?
Really it is necessary to enumerate each field of the form and to send them in such kind?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Shahob I, 2018-05-07
@bpGusar

<form name="person">
  <input name="name" value="Иван">
  <input name="surname" value="Иванов">
</form>

var object = {};
var formData = new FormData(document.forms.person);

formData.forEach(function(value, key){
    object[key] = value;
});
var json = JSON.stringify(object);

var xhr = new XMLHttpRequest();
xhr.open("POST", '/submit', true)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');

// Отсылаем объект в формате JSON и с Content-Type application/json
xhr.send(json);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question