繁体   English   中英

XMLHttpRequest 发送元数据但没有表单数据

[英]XMLHttpRequest sends meta data but no form data

我有一个 XMLHttpRequest,我想用它从我的表单中发送数据。 这是我的代码:

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"));

这实际上确实发送了一个带有元数据的请求,例如来源和引用者,但它不包含指定的文本字符串。

有谁知道我需要做什么才能将文本字符串与请求一起发送?

如果要将 json 发送到服务器,则应为 xhr.send 方法提供有效的 json 结构,如下所示:

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);

如果你想从一个发送值,你可以使用内置的 FormData object。 像这样:

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

您可以检查浏览器网络开发人员工具以确定哪些值已发送到服务器。

你也可以这样做。 xmlHttp function 处理创建 XMLHttpRequest object 在旧版浏览器中同样适用。 第二个 function fetchTask 是实际发送的内容。 要使用它,只需提供您的表格 object 作为参数。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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