[英]How to submit form without the page reloading
I have this form我有这个表格
<form action="" method="post" enctype="multipart/form-data" onsubmit="submit()">
<input id="name" class="btn" type="file" name="pic" multiple>
<br/><br/>
<button class="btn btn-primary" type="submit" id="submit" name="submit">UPLOAD</button>
</form>
<br/><br/>
Uploaded file: <a target="blank" href="<?php echo $fileurl;?>"><?php echo $fileurl;?></a>
and I have this script我有这个脚本
<script>
function submit(event) {
event.preventDefault()
var http = new XMLHttpRequest();
http.open("POST", "", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
</script>
I want to submit the form without the page reloading but isn't working for me.我想在不重新加载页面的情况下提交表单,但对我不起作用。
Your function takes event
property, on which you can invoke preventDefault()
您的 function 采用
event
属性,您可以在其上调用preventDefault()
function submit(event) {
event.preventDefault()
var http = new XMLHttpRequest();
http.open("POST", "", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
See this check function to stop page reloding请参阅此检查 function 以停止页面重载
As you have requested I have given the full code正如你所要求的,我已经给出了完整的代码
function check(event) { event.preventDefault(); console.log("stopped form submit"); }
<form onSubmit="check(event)"> <input id="name" class="btn" type="file" name="pic" multiple> <br/><br/> <button class="btn btn-primary" type="submit" id="submit" name="submit">UPLOAD</button> </form> <br/><br/> </form>
<script>
$('#yourFormData').submit(function(e){
e.preventDefault();
var formData = new FormData($('#yourFormData')[0]);
url ="your route" ;
$.ajax({
url : url,
type : "post",
data : formData,
contentType:false,
processData:false,
success : function(data)
{
// success
},
error : function(y)
{
console.log(error );
}
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.