使用javascript清除/重置formData() [英] clear/reset formData() using javascript
问题描述
我在下面使用formData,并传递结果。但是,如果用户不止一次重复数据,则会被复制。所以我必须在添加任何值之前清除/重置formData。
I use formData below, and pass the results. But data is duplicated if the user does it more than once. So I have to clear/reset the formData before adding any value.
我可以像f.name =''一样一对一地做,我有很多键。有没有更好的方法可以解决问题?
I can do it one-by-one like f.name = '', I have tons of keys. Is there any better way to solve the problem?
$('input').change(function(){
// Create a new formdata but at first have to clear/reset it
var fd = new FormData();
var f = $.canvasResize('dataURLtoBlob', data);
f.name = file.name;
fd.append($('#area input').attr('name'), f);
})
推荐答案
@ gurvinder372的答案不会从您的FormData中删除键,而是将其设置为空字符串,它不是服务器端。
例如,在php中, if(isset($ _ POST [ yourKey]))
@gurvinder372's answer won't remove your keys from your FormData, it will just set it to an empty string, which is not the same server side.
E.g, in php, if ( isset($_POST["yourKey"]) )
will still evaluate to true.
不幸的是,最好的跨浏览器方法是根据您的情况创建一个新的FormData对象。
The best crossbrowser way is unfortunately to create a new FormData object in your situation.
fd = new FormData();
另一种可能性,尽管目前仅受 Chrome> = 50 和 Firefox> = 39 ,将使用 formData.set()
方法。
该值将替换为
An other possibility, though it's currently only supported by Chrome>=50 and Firefox>=39, is to use the formData.set()
method.
This will replace the value at set key, or append it if no such key is there.
formData.set('yourKey', yourValue);
现在回答问题的标题,在 Chrome> = 50 和 Firefox> = 44 ,则可以使用 用于.. of formData.keys()
和您的FormData对象的删除
方法:
Now to answer the title of the question, in Chrome>=50 and Firefox>=44, you can use for .. of formData.keys()
and delete
methods of your FormData Object :
var formData = new FormData();
formData.append('yourKey', yourValue);
for (var key of formData.keys()) {
// here you can add filtering conditions
formData.delete(key)
});
,甚至使用 forEach
方法(显然
var formData = new FormData();
formData.append('yourKey', yourValue);
formData.forEach(function(val, key, fD){
// here you can add filtering conditions
formData.delete(key)
});
这篇关于使用javascript清除/重置formData()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!