我如何发送一个元素的id作为名称使用POST请求?



我使用了application/x-www-form-urlencoded,因为对于application/x-www-form-urlencoded,发送到服务器的HTTP消息的正文本质上是一个巨大的查询字符串——名称/值对由&号(&)分隔,名称与值由等号(=)分隔。这将是一个例子:MyVariableOne=ValueOne&MyVariableTwo=ValueTwo,但我想发送id作为一个变量,而不是作为一个值。如何将id作为变量发送?以下是我的程序:谢谢提前。

<HTML>
<head>
<script>
function fun1(element) {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/prc", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");    
xhttp.send(element.id);
//alert("ID":element.id);
}
</script>
</head>
<body>
<button type="button" onclick="fun1(this)" id="img1">IMAGE</button>
</body>
</html>

您必须创建一个FormData对象,将您的数据添加到该对象并发送该对象。参考本文档

var formData = new FormData();
formData.append("MyVariableOne", "ValueOne");
formData.append("id", 123456);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/prc", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");    
xhttp.send(formData);

最新更新