簡體   English   中英

使用document.getElementById附加formdata

[英]append formdata using document.getElementById

好的,下面的代碼正在發送文件名,但是對於表單數據,它發送了[object HTMLInputElement]或[object HTMLSelectElement],我需要更改什么以獲取表單中的值?

function _(el){
return document.getElementById(el); }

function uploadFile(){
var file = _("file1").files[0];
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("djname", _("djname"));
formdata.append("archive_date", _("archive_date"));
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "include/file_upload_parser.php");
ajax.send(formdata); }

一些形式

Date of Broadcast:
<input type='date' id='archive_date' name='archive_date' required>
Show Descripton (optional):<br>
<textarea rows='4' id='description' cols='50' name='description'>
<input type="file" name="file1" id="file1" accept="audio/mp3"><br>

您必須從元素中獲取值,就像從文件輸入中獲取文件一樣。

formdata.append("djname", _("djname").value);
formdata.append("archive_date", _("archive_date").value);

當您使用XMLHttpRequest時:

function ajax(a,b,e,d,c){// Url,callback,method,formdata
 c=new XMLHttpRequest;
 c.onload=b;
 c.open(e||'get',a);
 c.send(d||null)
}

有關ajax函數的更多信息

https://stackoverflow.com/a/18309057/2450730

HTML

<form id="form">
Date of Broadcast:
<input type='date' name='archive_date' required>
Show Descripton (optional):<br>
<textarea rows='4' cols='50' name='description'>
<input type="file" name="file1" accept="audio/mp3"><br>
</form>

多個文件

<input type="file" name="file[]" accept="audio/mp3" multiple>

JS

function fu(){alert('upload finished')}

window.onload=function(){
 var form=document.getElementById('form');
 form.onsubmit=function(e){
  e.preventDefault()
  ajax('include/file_upload_parser.php',fu,'post',new FormData(this));
  //or
  //ajax('include/file_upload_parser.php',fu,'post',new FormData(form));
 }
}

這將發送整個表格。

如您所見,無需為formdata和ajax +編寫此長代碼,您可以將ajax函數重用於其他用途。

編輯

具有進度處理程序的ajax函數。 f =上傳g =下載

function ajax(a,b,e,d,f,g,c){
 c=new XMLHttpRequest;
 !f||(c.upload.onprogress=f);
 !g||(c.onprogress=g);
 c.onload=b;
 c.open(e||'get',a);
 c.send(d||null)
}

所以

ajax('include/file_upload_parser.php',fu,'post',new FormData(form),progressHandler);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM