表单validation和HTML修改
描述:
我试图validation服务器端的<form>
。 为此,我使用AJAX将表单input以JSONforms发送到后端(一个express.js应用程序)。 validation之后,我把这个结构发送到另一个JSON的前端:
{ input1: true|false, ... inputN: true|false }
( true
对错错误)
现在,在前端如果一个input是错误的, <span>
被添加到<input>
旁边,表明它是不正确的。 如果这是正确的发生相同的,但表明<input>
是正确的。
问题出现在前端响应的后端,AJAX调用失败和IDK为什么。
HTML代码:
<!DOCTYPE html> <html> <head> <script src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> function submitForm() { $('span').remove(); let req = $.ajax({ url: 'http:localhost:3000/validate', dataType: 'json', data: $('#myForm').serializeArray() }); req.done((data, textStatus, jqXHR) => { alert('OK'); for (input in data) { let elem = '<span style="color: green">OK</span>'; if (!data[input]) elem = '<span style="color: red">ERROR</span>'; $('#${input}').append(elem); } }); req.fail((jqXHR, textStatus, errorThrown) => { alert('ERROR'); }); } </script> </head> <body> <form id="myForm"> <div id="name"> <input type="text" name="name" placeholder="Name"> </div> <div id="surname"> <input type="text" name="surname" placeholder="Surname"> </div> <input type="submit" onclick="submitForm()"> </form> </body> </html>
已编辑的HTML代码:
<!DOCTYPE html> <html> <body> <form id="myForm"> <div id="name"> <input type="text" name="name" placeholder="Name"> </div> <div id="surname"> <input type="text" name="surname" placeholder="Surname"> </div> <input type="button" value="Send" onclick="submitForm()"> </form> <script src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> function submitForm() { $('span').remove(); let req = $.ajax({ url: 'http:localhost:3000/validate', dataType: 'json', data: $('#myForm').serializeArray() }); req.done((data, textStatus, jqXHR) => { alert('OK'); for (input in data) { let elem = '<span style="color: green">OK</span>'; if (!data[input]) elem = '<span style="color: red">ERROR</span>'; $('#${input}').append(elem); } }); req.fail((jqXHR, textStatus, errorThrown) => { alert('ERROR'); }); } </script> </body> </html>
NodeJS代码:
const express = require('express'); const app = express(); app.get('/validate', (req, res) => { let query = req.query; let obj = {}; obj.name = query.name == 'Marco'; obj.surname = query.surname == 'Canora'; console.log(obj); res.json(obj); }); app.listen(3000, () => { console.log('App is listening'); });
浏览器控制台
http://localhost:3000/validate?name=Marco&surname=Canora. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
BTW:
使用jsonpCallback似乎工作,但我不明白如何和为什么工作。
jsonpCallback函数不工作
将此添加到app.js
解决scheme的问题:
app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
https://enable-cors.org/server_expressjs.html
来自express js的Ajax post响应不断抛出错误