I have a simple HTML form
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function sendFormData(){
var formData = JSON.stringify($("#myForm").serializeArray());
$.ajax({
type: "POST",
url:"http://localhost:3000/test",
data: formData,
sucess: function(){
alert("something!");
},
error: function(textstatus, errorThrown) {
alert('text status ' + textstatus + ', err ' + errorThrown);
}
});
}
</script>
</head>
<body>
<form id="myForm">
Name: <input type="text" name="name">
Address: <input type="text" name="address">
<input type="submit" value="Submit" onClick="sendFormData()">
</form>
</body>
</html>
我将使用Node.js将数据发送到服务器。
server.js
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
// Express
var app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
// Get information submitted
app.post('/test', function(req, res) {
console.log("Information received !");
console.log(req.body);
res.send("Ok!");
});
// Start server
app.listen(3000);
console.log("API is running on port 3000");
我有两个问题。
- 我是否正确地将表单中提取的数据发送到服务器?我可以在控制台中看到值,但网页仍在加载。我只想发送数据,显示警报并保持在相同页面上,同时清除表单字段。
- 在将数据发送到服务器之前或之后,我应该验证表单中的数据(以及如何验证)?例如,确保没有数字插入到字段名称中,或者字段名称应小于30个字符。
XMLHttpRequest cannot load http://localhost:3000/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
提前感谢!