[英]dynamically created HTML file input element doesn't post data
我有一個使用 document.createElement 動態創建的表單。 組件的創建方式相同。 該表單用於將文件上傳到 PHP 腳本,並在提交時加載表單目標屬性指定的 iframe 中的響應。
不幸的是,服務器收到一個空白的 $_FILES 數組,當我檢查 POST 請求時,我發現文件數據未包含在請求中。 如果我改為使用 Google Chrome 開發人員工具動態編輯動態創建的表單(在此過程中,我只是編輯然后絕對不更改任何代碼),然后表單提交工作完美,發送相關文件數據.
所以這讓我意識到我在 html 中的表單構造沒有任何問題,因為它沒有任何改變就可以工作。 這讓我相信瀏覽器不喜歡我動態創建文件輸入元素?
為了完整起見,這里是動態生成的表格:
<form method="POST" action="includes/uploadPic.php"
enctype="multipart/form-data" target="fileResponse">
<input type="file" name="pic">
<input type="submit" value="Upload">
</form>
並且print_r($_FILES)
在服務器上給出一個空數組。
誰能給我解釋一下? 我的替代方法是在文檔中靜態創建一個隱藏表單,並在需要時將其 append 放到相關的 div 中,但我真的不喜歡那種東西。
下面是生成表單的代碼:
var form = document.createElement("form");
var fileUpload = document.createElement("input");
var uploadBut = document.createElement("input");
form.setAttribute("method", "POST");
form.setAttribute("action", "includes/uploadPic.php");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("target", "fileResponse");
fileUpload.setAttribute("type", "file");
fileUpload.setAttribute("name", "pic");
uploadBut.setAttribute ("type", "submit");
uploadBut.setAttribute ("value", "Upload");
form.appendChild(fileUpload);
form.appendChild(uploadBut);
dlgContent.appendChild(form);
如果將form
標簽放在div
標簽中,它不會將動態創建的元素發布到服務器。 但是,如果你把它放在div
或table
標簽之外,它就可以工作。
嘗試這個:
var form = document.createElement("form");
var fileUpload = document.createElement("input");
var uploadBut = document.createElement("input");
form.method = "POST";
form.action = "includes/uploadPic.php";
form.enctype = "multipart/form-data";
form.target = "fileResponse"; /* I think you are trying to submit this from in an iframe */
fileUpload.type = "file";
fileUpload.name = "pic";
uploadBut.type = "submit";
uploadBut.value = "Upload";
form.appendChild(fileUpload);
form.appendChild(uploadBut);
dlgContent.appendChild(form);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.