我从一份教程中复制了一些代码,该代码将表单内容发送到一个API。API在AWS上设置正确,如果我使用Postman发送一些JSON,它就能正常工作。但是JavaScript却不能正常工作。当我点击表单提交按钮时,sendDataToLambda函数不执行。如果我在提交按钮上添加onClick="sendDataToLambda()",那么函数就会触发(但是在e.preventDefault()行出现失败,这是预期的行为)。
我已经检查过表单ID是否正确以及是否正确设置了侦听器,但是我找不到问题所在。 如可能尽量不使用jQuery库。
我已经检查过表单ID是否正确以及是否正确设置了侦听器,但是我找不到问题所在。 如可能尽量不使用jQuery库。
<body>
<div class=container>
<h1>Notes</h1>
<form id="note-form" style="margin-top:50px;">
<input type="text" id="subject" placeholder="Enter subject here…" class="form-control" /><br/>
<textarea id="body" rows="3" placeholder="Enter body here…" class="form-control"></textarea><br/>
<button type="button" class="btn btn-lg">Submit</button>
</form>
</div>
<script type="text/javascript">
// Adds an event listener to our form. When the form is submitted, it will send data to our Lambda function, which in turn, will send us an email.
document.getElementById('note-form').addEventListener('submit', sendDataToLambda);
// Now for the good stuff. This is the function that will send our data to AWS.
function sendDataToLambda(e) {
console.log('Submit clicked')
e.preventDefault();
// Gets the values of each field in our form. This is the data we'll send to our Lambda function.
var formSubject = document.getElementById('subject').value;
var formBody = document.getElementById('body').value;
// This is the endpoint we created in our API Gateway. This is where we make our POST request, which calls our Lambda function.
var endpoint = 'https://################';
// Remember those form values we just grabbed? We're going to put them into an object here.
var body = {
subject: formSubject,
body: formBody
}
// Here, we instantiate our Request. This is a special object used by the Fetch API so it knows where to send data, what data to send, and how to send it.
var lambdaRequest = new Request(endpoint, {
method: 'POST',
// Quick note: 'no-cors' mode is for development on localhost only!
mode: 'no-cors',
body: JSON.stringify(body)
});
// Call the Fetch API to make our request
fetch(lambdaRequest)
// This is where you can handle errors. This is just an example, so we won't cover that.
.then(response => console.log(response))
.catch(err => console.log(err));
}
</script>
</body>
</html>
<input type="submit">
,所以它不会触发onsubmit
。 - Niet the Dark Absol<button type="submit" class="btn btn-lg">提交</button>
- mplungjan