我有一个HTML表单来获取用户输入,我希望使用客户端Javascript将表单数据转换为JSON。
See UPDATE below for code~
假设参数信息正确,如何使用JS发布到API?
更新:
这对我有用:
<div class="uk-width-1-1">
<p class="uk-button uk-button-default uk-margin" id="demo" onclick="myFunction()">Submit</p>
</div>
<script>
function myFunction() {
// Data discovery
console.log("Getting info");
var d = new Date(); // Now
var n = d.getTime(); // getTime for milliseconds since epoch
var dateTime = String(n); // Stringifying
var name = document.getElementById("logForm-name").value; // Form data
var employee = document.getElementById("logForm-employee").value; // Form data
var comments = document.getElementById("logForm-comments").value; // Form data
var params =
{
"dateID": dateTime,
"visitorName": name,
"employeeName": employee,
"comments": comments
};
JSON.stringify(params); // stringifying
// Sending data
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "API URL";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
console.log("Sending...");
xmlhttp.send(JSON.stringify(params));
document.getElementById("demo").style.color = "green"; // Visual for success
console.log("Item added to DDB.");
// Reset Form
document.getElementById('logForm').reset()
}
</script>
答案 0 :(得分:0)
使用xmlHTTPrequest从正文中调用数据。 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest