不使用Ajax,如何實現表單提交不刷新頁面?
目前,我想到的是使用<iframe>
,如果有其他的方式,后續再補。
舉個栗子:
在表單上傳文件的時候必須設置enctype="multipart/form-data"
表示表單既有文本數據,又有文件等二進制數據。但是使用用Ajax沒有enctype="multipart/form-data"
,所以不能直接上傳文件,所以采用FormData
對象包含數據上傳。
這里我們不使用Ajax,直接提交表單,添加一個隱藏得iframe,將form表單的target
指向這個iframe來阻止刷新并且上傳文件。
<form method="POST" action="./upload.php" enctype="multipart/form-data" target='ifr' id="form1"><label for="name">name:</label><input type="text" id="name" name="name"/><br/><input type="file" name="file" ><input type="submit" value="提交">
</form>
接著,我們要獲取返回值
var iframe=document.getElementById("ifr");iframe.onload= function () {var bodycontent=iframe.contentDocument.body.innerHTML;console.log(bodycontent);//處理獲取到的內容;}
這樣的話基本上可以模擬ajax的操作,實現無刷新提交表單。 完整代碼:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<form method="POST" action="./upload.php" enctype="multipart/form-data" target='ifr' id="form1"><label for="name">name:</label><input type="text" id="name" name="name"/><br/><input type="file" name="file" ><input type="submit" value="提交">
</form>
<iframe name='ifr' id="ifr" style='display: none;'></iframe>
<script>
var iframe=document.getElementById("ifr");iframe.onload= function () {var bodycontent=iframe.contentDocument.body.innerHTML;console.log(bodycontent);//處理獲取到的內容;}</script>
</body>
</html>
//php代碼<?phpecho "name:".$_POST['name'].";filename:".$_FILES['file']['name'];