send key value pair array by post in javascript

To send a key-value pair array in a POST request in JavaScript, you can use the XMLHttpRequest object to create the request and JSON.stringify to serialize the data in JSON format. Here's an example:

index.tsx
const data = {key1: 'value1', key2: 'value2', key3: 'value3'};
const url = 'http://example.com/api';
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log('Response:', xhr.responseText);
  } else {
    console.error('Error:', xhr.statusText);
  }
};
xhr.onerror = function() {
  console.error('Error:', xhr.statusText);
};
xhr.send(JSON.stringify(data));
506 chars
17 lines

In this example, we define an object data with some key-value pairs. We also specify the URL of the API endpoint in url. Then, we create a new XMLHttpRequest object and open a POST request to the specified URL. We set the Content-Type header to indicate that we're sending JSON data. We define the onload and onerror event handlers to handle the response or error. Finally, we send the POST request with the serialized JSON data using the send method.

gistlibby LogSnag