Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 如何检查FormData?(How to inspect FormData?)

I've tried console.log and looping through it using for in .

(我已经尝试过console.log并使用for in循环。)

Here it the MDN Reference on FormData.

(这里是FormData上的MDN参考 。)

Both attempts are in this fiddle .

(两种尝试都在摆弄 。)

var fd = new FormData(),
    key;

// poulate with dummy data

fd.append("key1", "alskdjflasj");
fd.append("key2", "alskdjflasj");

// does not do anything useful

console.log(fd);

// does not do anything useful

for(key in fd) {
    console.log(key);
}

How can I inspect form data to see what keys have been set.

(如何检查表单数据以查看设置了哪些键。)

  ask by translate from so

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

1 Reply

0 votes
by (71.8m points)

Updated Method:

(更新方法:)

As of March 2016, recent versions of Chrome and Firefox now support using FormData.entries() to inspect FormData.

(从2016年3月开始,Chrome和Firefox的最新版本现在支持使用FormData.entries()检查FormData。)

Source .

(来源 。)

// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

// Display the key/value pairs
for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); 
}

Thanks to Ghost Echo and rloth for pointing this out!

(感谢Ghost Echorloth指出了这一点!)

Old Answer:

(旧答案:)

After looking at these Mozilla articles , it looks like there is no way to get data out of a FormData object.

(看完这些 Mozilla 文章之后 ,似乎无法从FormData对象中获取数据。)

You can only use them for building FormData to send via an AJAX request.

(您只能将它们用于构建通过AJAX请求发送的FormData。)

I also just found this question that states the same thing: FormData.append("key", "value") is not working .

(我也刚刚发现这个问题指出了同样的问题: FormData.append(“ key”,“ value”)不起作用 。)

One way around this would be to build up a regular dictionary and then convert it to FormData:

(解决此问题的一种方法是建立一个常规词典,然后将其转换为FormData:)

var myFormData = {
    key1: 300,
    key2: 'hello world'
};

var fd = new FormData();
for (var key in myFormData) {
    console.log(key, myFormData[key]);
    fd.append(key, myFormData[key]);
}

If you want to debug a plain FormData object, you could also send it in order to examine it in the network request console:

(如果要调试普通的FormData对象,也可以发送它以便在网络请求控制台中检查它:)

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(fd);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...