Tengo un XMLHttpRequest que quiero usar para enviar datos desde mi formulario. Aquí está mi código:
var mc_xhr = new XMLHttpRequest(); mc_xhr.open( "POST", "https://webhook.site/58493d5a-9b8d-4300-875b-8f4d5ec6665b" ); mc_xhr.setRequestHeader("Content-Type", "application/json"); mc_xhr.send(JSON.stringify("test-string"));En realidad, esto envía una solicitud con metadatos como el origen y la referencia, pero no contiene la cadena de texto especificada.
¿Alguien sabe qué debo hacer para enviar la cadena de texto con la solicitud?
Puedes hacerlo así también. La función xmlHttp maneja la creación del objeto XMLHttpRequest que funcionará igual de bien en navegadores más antiguos. La segunda función, fetchTask, es lo que realmente hace el envío. Para usarlo, simplemente proporcione su objeto de formulario como argumento.
function xmlHttp() { if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!xhr) { console.log('Giving up :( Cannot create an XMLHTTP instance'); return false; } } // The function that takes the xmlHttp function, send your data and uses the response function fetchTask(frmElement) { xmlHttp(); xhr.onload = function() { const rsp = JSON.parse(xhr.responseText) } xhr.open(frmElement.method, frmElement.action, true) xhr.send(new FormData(frmElement)) return false } // Grab the form to be sent taskForm = document.querySelector('#task-form') // Do the actual sending fetchTask(taskForm)Si desea enviar un json al servidor, debe proporcionar una estructura json válida para el método xhr.send como este:
let xhr = new XMLHttpRequest(); let body= JSON.stringify({ name: "Saeed", family: "Shamloo" }); xhr.open("POST", '/targetURL') xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8'); xhr.send(body);Si desea enviar valores desde un formulario, puede usar el objeto FormData integrado. como esto:
<form name="person"> <input name="name" value="Saeed"> <input name="family" value="Shamloo"> </form> <script> // pre-fill FormData from the form let formData = new FormData(document.forms.person); // add one more custom field formData.append("middle", "middle-name"); let xhr = new XMLHttpRequest(); xhr.open("POST", "/targetURL"); xhr.send(formData); </script>Puede consultar la herramienta de desarrollo de la red del navegador para determinar qué valores se han enviado al servidor.