Uncaught TypeError: Невозможно прочитать свойство 'init' из неопределенного в Javascript при отправке формы - PullRequest
0 голосов
/ 29 мая 2019

Я пытаюсь создать мини-веб-приложение для социальных сетей, используя модуль python web.py.Я сделал регистрационную форму в html, но когда я заполняю детали и отправляю их, консоль браузера показывает следующий вывод:

Uncaught TypeError: $(...).ready(...) is not a function
at scripty.js:22
loaded
jquery-3.4.1.min.js:2 Uncaught TypeError: Cannot read property 'init' of undefined
at HTMLDocument.<anonymous> (scripty.js:4)
at e (jquery-3.4.1.min.js:2)
at t (jquery-3.4.1.min.js:2)

Я искал похожие проблемы, но их решения, похоже, не нашлиработать для этого случая.

Вот мой код файла "scripty.js"

$(document).ready(function () {
    console.log("loaded");

    $.material.init();

    $(document).on("submit", "#register-form", function (e) {
        e.preventDefault();
        console.log("form submitted");

        let form = $('#register-form').serialize(); //get the form data

        //send an ajax request over to the route /postregisteration
        $.ajax({
            url: '/postregisteration',
            type: 'POST',
            data: form,
            success: function (response) {
                console.log(response);
            }
        });
    });
})();

А вот код файла controller.py в python

import web
from Models import RegisterModel


urls = (
    '/', 'Home',
    '/register', 'Register',
    '/postregistration', 'PostRegistration'
)

render =  web.template.render("Views/Templates", base="MainLayout")

app = web.application(urls, globals())


# Classes/Routes
# Each class will be controlling a route

class Home:
    def GET(self):
        return render.Home()

class Register:
    def GET(self):
        return render.Register()

class PostRegistration:
    def POST(self):
        data = web.input()
        print(data.username)

        reg_model = RegisterModel.RegisterModel.insert_user(data)
        return data.username


if __name__=="__main__":
    app.run()

После нажатия кнопки «Отправить» он просто печатает «загружен» и отображает ошибку на консоли браузера.

Но также должен отображаться «отправленный бланк».

Любая помощь будет полезна.

Ответы [ 2 ]

1 голос
/ 29 мая 2019

Вот ваш скрипт с исправленной ошибкой в ​​конце строки, удалением материала и добавлением комментариев, объясняющих, что делает каждая строка.

// Wait until the page has fully loaded before applying the script
$(document).ready(function () {
    // Bind a function to the submit form
    $(document).on("submit", "#register-form", function (e) {
        // Prevent the default form post behavior to prevent the page from reloading
        e.preventDefault();

        // Get the form data
        var form = $('#register-form').serialize(); 

        // Send an ajax request over to the route /postregisteration
        $.ajax({
            url: '/postregisteration',
            type: 'POST',
            data: form,
            success: function (response) {
                console.log("form submitted");
                console.log(response);
            }
        });
    });
});
1 голос
/ 29 мая 2019

Измените последнюю строку JS, которую вы показали:

С

})();

до

});

Это исправляет вашу первую ошибку ... is not a function.

Для второй ошибки это означает, что $.material равно undefined. Либо удалите его (если вы не используете дизайн материала), либо убедитесь, что соответствующий плагин доступен.

...