表单验证和HTML修改

时间:2017-09-02 10:37:54

标签: jquery html node.js ajax express

说明

我正在尝试验证服务器端的<form>。为此,我使用AJAX将表单输入JSON发送到后端(express.js应用程序)。验证之后,我向前端发送另一个具有以下结构的JSON:

{
     input1: true|false,
     ...
     inputN: true|false
}

true是正确的,false错误的)

现在,在前端,如果一个输入错误,<span>旁边会添加<input>,表示它不正确。如果它是正确的,但表明<input>是正确的。

问题出现在前端响应的后端,AJAX调用失败,IDK为什么。

HTML code:

<!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.

顺便说一句:

使用jsonpCallback似乎有效,但我不明白为何以及为何有效。

jsonpCallback function not working

1 个答案:

答案 0 :(得分:1)

将此问题添加到app.js解决问题:

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

Ajax post response from express js keeps throwing error