js想獲取FormData 對象中的所有元素,很可惜有兼容性問題。一般高版本瀏覽器能使用,如谷歌,火狐等,但在IE 中entries並不存在,而且FormData僅能使用 append 方法,於是我重寫FormData 對象,目前使用過程中還沒發現什麼問題。
// 遍歷方法1:存在兼容問題
var ent = data.entries();
var item = ent.next();
while(!item.done){
console.log(item.value[0] + "=" + item.value[1])
item = ent.next();
}
// 遍歷方法2:需要重寫append方法
// >> 定義變量,記錄原始append方法
FormData.prototype._myAppend = FormData.prototype.append;
// >> 重寫append方法
FormData.prototype.append = function (name, value, fileName) {
// 臨時對象,記錄元素
this.data = this.data!=undefined?this.data:{};
this.data[name] = value;
if (fileName) {
this._myAppend(name, value, fileName);
} else {
this._myAppend(name, value);
}
};
// >> 遍歷
FormData formData = new FormData();
formData.append("name", "李翔飛");
formData.append("sex", "男);
for (var key in formData.data) {
console.log(key + "=" + formData.data[key]);
}
嘿嘿,如果可以用,給個贊鼓勵下吧。