我已经使用javascript / jquery / ajax和php single page application w/ add document button创建了一个单页应用程序
单击添加文档按钮后,由javascript函数创建的动态表单将显示dynamic form created by javascript function
单击“添加文档”按钮后,必须将FormData提交到单独的php代码,但是我无法提交FormData,并且页面将刷新。
//function that will create a form
function addDocument(obj){
var category=obj.value;
var btnId=obj.id;
console.log(obj.id);
$('.centercon').html("<div class='maincontent'></div>"+
"<div class='filecontent'><h1></h1></div>");
$('.filecontent').html("<i class='fa fa-folder-o'></i>"+category+"/..."+
"<form class='file' method='POST' action='' id='document' enctype='multipart/form-data'>"+
"<input type='hidden' name='category' value='"+category+"'/>"+
"<input type='hidden' name='buttonID' value='"+btnId+"'/>"+
"<button class='btn btn-success adddocument' type='submit'>Add Document</button>"+
"<div class='row'><div class='col-lg-4'><input type='text' class='form-control' name='docuName' placeholder='Document Name'></div>"+
"<div class='col-lg-4'><input type='text' name='designate' class='form-control' placeholder='Designation'></div>"+
"<div class='col-lg-4'><input type='text' name='addInfo' class='form-control' placeholder='Additional Details'></div></div>"+
"<input type='file' class='form-control fileInput' name='document' placeholder='Additional Details' onchange='readURL(this);'><hr>"+
" <img id='previewDocument' src='#' width='100%' alt='Preview Document'/></form>");
}
//function for submitting a FormData once the Add Document button was pressed
$("#document").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "/main.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
}
});
}));
我试图仅使用php直接提交表单,这是可行的。我还尝试使用表单和提交表单数据的功能创建一个单独的页面,但是它也可以使用。
您能否告诉我创建单页应用程序的方法或提供其他替代方法。
答案 0 :(得分:1)
如果您正在将表单动态添加到dom,则需要将提交处理程序更改为这样的内容。
$(function () {
$(document).on('submit', '#document', function (e) {
//do stuff
});
}
查看更多
答案 1 :(得分:0)
我尝试了多次您的代码,结果与您收到的结果相同, 但只需稍作更改,就可以实现您想要的
以标签形式放置此属性:
<form onsubmit="yourFunction(event)" class='file' method='POST' action='' id='document' enctype='multipart/form-data'>
然后使用js代码创建yourFunction,不要忘记将event.preventDefault();放进去。在里面
function yourFunction(event){
event.preventDefault();
//...
}
希望它能对您有所帮助。