【发布时间】:2020-06-24 19:12:24
【问题描述】:
我在单击按钮时使用Javascript 动态创建了一个表单,然后我想使用JQuery 和Ajax 处理提交事件,但它不起作用,它将我重定向到操作字段(顺便说一下空白页)并且不触发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)
});
Ajax
$("#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>
【问题讨论】:
-
你有没有尝试在div.appendChild(form)下面添加这个函数;
标签: javascript jquery ajax forms