【发布时间】:2018-01-25 23:31:34
【问题描述】:
问一个已经有多个答案和多次的问题可能是个坏主意,但无论如何我应该问它。我几乎尝试了在那里找到的所有东西Prevent redirect after form is submitted,但没有任何帮助。 有一个小细节,我看不到。我对 jQuery 和 AJAX 不是很熟悉。尤其是前者。 所以,代码:
<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br>
<label id="nameerror"></label><br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br>
<label id="emailerror"></label><br>
Select a file<br />
<label id="draganddroperror"></label><br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br />
<button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button>
</form>
有我的JS
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val() != "") {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
return false;
}
});
return false; //event.preventDefault();
} else {
alert("Please select file!");
}
}
所以,这是有问题的代码。除重定向外,所有工作都完美无缺。另一个问题包含提交,但我没有提交输入。我试图将表单与 post 方法(第一行)断开,但出现服务器错误。到处都返回 false。 我在这个问题上花了无数个小时,这几天几乎耗尽了我所有的夜间时间。我会很感激任何帮助,谢谢。
【问题讨论】:
-
你的
return false不应该在else子句之后吗? -
我不这么认为。 else 子句不发布任何内容。
-
<button>的点击事件本身就是一个post动作。 -
我想你不明白为什么你会返回 false。你基本上没有在你引用的那篇文章中尝试过任何东西。我没有看到您阻止对事件的默认操作(您没有费心将其传递给单击处理程序)。我也没有看到您返回 false 来阻止默认操作。
-
当您的表单中没有
<button type="submit"></button>时,每个按钮都充当type="submit"
标签: javascript jquery ajax forms