javascript FormData 兼容遍历问题

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]);
}

嘿嘿,如果可以用,给个赞鼓励下吧。

发布了6 篇原创文章 · 获赞 5 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章