首页 > 解决方案 > 创建 Javascript 表单后 Ajax 无法正常工作

问题描述

我在单击按钮时动态创建了一个表单Javascript,然后我想用它来处理提交事件,JQueryAjax它不起作用,它将我重定向到操作字段中的 url(顺便说一下空白页)而不触发事件JQuery。尝试了一些我发现但仍然无法正常工作的解决方案。

JS表格

$("#createForm").on("click", function (e) {

    var div = document.getElementById('createTopic');
    var form = document.createElement('form');
    form.setAttribute('id', 'topicForm');
    form.setAttribute('action', "/post/" + postId + "/topic/create");
    form.setAttribute('method', 'POST');

    var csrf = document.createElement('input');
    csrf.setAttribute("type","hidden");
    csrf.setAttribute("name","_token");
    csrf.setAttribute("value",csrf_token);

    var input1 = document.createElement('input');
    input1.setAttribute('type', 'text');
    input1.setAttribute('placeholder', 'Name');
    input1.setAttribute('name', 'topicName');

    var input2 = document.createElement('input');
    input2.setAttribute('type', 'text');
    input2.setAttribute('placeholder', 'Color');
    input2.setAttribute('name', 'topicColor');


    var submit = document.createElement('input');
    submit.setAttribute('type', 'submit');
    submit.setAttribute("value", "Crear");
    submit.setAttribute('id', 'createTopic');

    form.appendChild(csrf);
    form.appendChild(input1);
    form.appendChild(input2);
    form.appendChild(submit);

    div.appendChild(form)
});

阿贾克斯

$("#topicForm").on("submit", function (e) {

    e.preventDefault();
    var form = $(this);

    $.ajax({
        url: form.attr('action'),
        type: "post",
        data: form.serialize(),
        headers: {'X-CSRF-Token': csrf_token},
        success: function (response) {
            console.log("SUCCESS: " + response);
        },
        error: function (jqXHR, exception) {
            var msg = '';
            if (jqXHR.status === 0) {
                msg = 'Not connect.\n Verify Network.';
            } else if (jqXHR.status == 404) {
                msg = 'Requested page not found. [404]';
            } else if (jqXHR.status == 500) {
                msg = 'Internal Server Error [500].';
            } else if (exception === 'parsererror') {
                msg = 'Requested JSON parse failed.';
            } else if (exception === 'timeout') {
                msg = 'Time out error.';
            } else if (exception === 'abort') {
                msg = 'Ajax request aborted.';
            } else {
                msg = 'Uncaught Error.\n' + jqXHR.responseText;
            }
            console.log("ERROR: " + msg);
        },
    });
});

HTML

<div style="float: right;width:150px;">
   <button id=createForm class="btn btn-warning btn-sm"> Add topic <i class="fa fa-plus"></i></button>
</div>

<div id="createTopic" style="float: right;width:150px;"></div>

标签: javascriptjqueryajaxforms

解决方案


    $("#createForm").on("click", function (e) {

    var div = document.getElementById('createTopic');
    var form = document.createElement('form');
    form.setAttribute('id', 'topicForm');
    form.setAttribute('action', "/post/" + postId + "/topic/create");
    form.setAttribute('method', 'POST');

    var csrf = document.createElement('input');
    csrf.setAttribute("type","hidden");
    csrf.setAttribute("name","_token");
    csrf.setAttribute("value",csrf_token);

    var input1 = document.createElement('input');
    input1.setAttribute('type', 'text');
    input1.setAttribute('placeholder', 'Name');
    input1.setAttribute('name', 'topicName');

    var input2 = document.createElement('input');
    input2.setAttribute('type', 'text');
    input2.setAttribute('placeholder', 'Color');
    input2.setAttribute('name', 'topicColor');


    var submit = document.createElement('input');
    submit.setAttribute('type', 'submit');
    submit.setAttribute("value", "Crear");
    submit.setAttribute('id', 'createTopic');

    form.appendChild(csrf);
    form.appendChild(input1);
    form.appendChild(input2);
    form.appendChild(submit);

    div.appendChild(form)

    $("#topicForm").on("submit", function (e) {

    e.preventDefault();
    var form = $(this);

    $.ajax({
        url: form.attr('action'),
        type: "post",
        data: form.serialize(),
        headers: {'X-CSRF-Token': csrf_token},
        success: function (response) {
            console.log("SUCCESS: " + response);
        },
        error: function (jqXHR, exception) {
            var msg = '';
            if (jqXHR.status === 0) {
                msg = 'Not connect.\n Verify Network.';
            } else if (jqXHR.status == 404) {
                msg = 'Requested page not found. [404]';
            } else if (jqXHR.status == 500) {
                msg = 'Internal Server Error [500].';
            } else if (exception === 'parsererror') {
                msg = 'Requested JSON parse failed.';
            } else if (exception === 'timeout') {
                msg = 'Time out error.';
            } else if (exception === 'abort') {
                msg = 'Ajax request aborted.';
            } else {
                msg = 'Uncaught Error.\n' + jqXHR.responseText;
            }
            console.log("ERROR: " + msg);
        },
    });
});

});

推荐阅读