使用JQuery AJAX methods将让您的信息发送和接收到指定的URL,而无需刷新页面。
您需要将JQuery库包含在HTML页面中。您可以下载它,并把它放在你的项目文件夹或这里包括在线图书馆,像这样:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
所以你的形式会是这个样子的:
<form id="myForm" method="post" >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
<input type="submit">
</form>
然后你就可以使用这个代码简单地上传图片到你的文件上传页面(测试和工作为自己):
<script>
$(document).ready(function()
{
$("#myForm").submit(function (e)
{
//Stops submit button from refreshing page.
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
url: 'http://example/DB_1/AccessWeb/file_upload.php', //location of where you want to send image
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response)
{
alert('success');
},
error: function()
{
alert('failure');
}
});
});
});
</script>
你能澄清这个问题好吗?您不希望表单在处理上载后发布到'file_upload.php'或重定向? – RamRaider
是的,我需要上传文件,当点击上传按钮,但不想重定向file_upload.php,而是留在同一页面。 – CodeDezk
两个选项,我看到它:具有POST形式到同一页面(意味着在同一页面上处理上传的php代码)或'file_upload.php'使用'header('Location:page.php' );'where page.php'是表单的网页名称。第三个选项 - 使用ajax – RamRaider