Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

jquery - clear/reset formData() using javascript

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.

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);
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@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.


The best crossbrowser way is unfortunately to create a new FormData object in your situation.

fd = new FormData();

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

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

or even with its forEach method (apparently with the same poor browser support)

var formData = new FormData();
formData.append('yourKey', yourValue);

formData.forEach(function(val, key, fD){
    // here you can add filtering conditions
    formData.delete(key)
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...