Javascript FormData.append("key", "value") 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7752188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:27:35  来源:igfitidea点击:

FormData.append("key", "value") is not working

javascripthtmlform-data

提问by netzaffin

Can you tell me whats wrong with this:

你能告诉我这有什么问题吗:

var formdata = new FormData();
formdata.append("key", "value");
console.log(formdata);

My output looks like this, I cant find my "key" - "value" pair

我的输出看起来像这样,我找不到我的“键”-“值”对

FormData
*__proto__: FormData
**append: function append() { [native code] }
***arguments: null
***caller: null
***length: 0
***name: "append"
***prototype: append
***__proto__: function Empty() {}
*constructor: function FormData() { [native code] }
**arguments: null
**caller: null
**length: 0
**name: "FormData"
**prototype: FormData
**toString: function toString() { [native code] }
*__proto__: Object
**__proto__: Object
**__defineGetter__: function __defineGetter__() { [native code] }
**__defineSetter__: function __defineSetter__() { [native code] }
**__lookupGetter__: function __lookupGetter__() { [native code] }
**__lookupSetter__: function __lookupSetter__() { [native code] }
**constructor: function Object() { [native code] }
**hasOwnProperty: function hasOwnProperty() { [native code] }
**isPrototypeOf: function isPrototypeOf() { [native code] }
**propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
**toLocaleString: function toLocaleString() { [native code] }
**toString: function toString() { [native code] }
**valueOf: function valueOf() { [native code] }

I can't understand! Yesterday it worked so well, and today my head crashed the keyboard so many times! Firefox, Chrome, both the same :/

我无法理解!昨天它运行得很好,今天我的头撞了键盘很多次!Firefox,Chrome,都一样:/

回答by Rudie

New in Chrome 50+ and Firefox 39+ (resp. 44+):

Chrome 50+ 和 Firefox 39+(分别为 44+)中的新功能:

  • formdata.entries()(combine with Array.from()for debugability)
  • formdata.get(key)
  • and more very useful methods
  • formdata.entries()(结合Array.from()可调试性)
  • formdata.get(key)
  • 以及更多非常有用的方法

Original answer:

原答案:

What I usually do to 'debug' a FormDataobject, is just send it (anywhere!) and check the browser logs (eg. Chrome devtools' Network tab).

我通常用来“调试”一个FormData对象,只是将它发送(任何地方!)并检查浏览器日志(例如 Chrome devtools 的“网络”选项卡)。

You don't need a/the same Ajax framework. You don't need any details. Just send it:

您不需要相同的 Ajax 框架。你不需要任何细节。只需发送它:

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

Easy.

简单。

回答by Jesper

You say it's not working. What are you expecting to happen?

你说它不起作用。你期待发生什么?

There's no way of getting the data out of a FormDataobject; it's just intended for you to use to send data along with an XMLHttpRequestobject (for the sendmethod).

无法从FormData对象中获取数据;它只是供您用来与XMLHttpRequest对象(对于send方法)一起发送数据。

Update almost five years later: In some newer browsers, this is no longer true and you can now see the data provided to FormDatain addition to just stuffing data into it. See the accepted answerfor more info.

近五年后更新:在一些较新的浏览器中,这不再是真实的,您现在可以看到所提供的数据FormData,而不仅仅是将数据塞入其中。有关更多信息,请参阅已接受的答案

回答by CodeGodie

You might have been having the same problem I was initially having. I was trying to use FormData to grab all my input files to upload an image, but at the same time I wanted to append a session ID to the information passed along to the server. All this time, I thought by appending the information, you would be able to see it in the server by accessing the object. I was wrong. When you append to FormData, the way to check the appended information on the server is by a simple $_POST['*your appended data*']query. like so:

您可能遇到了与我最初遇到的相同的问题。我试图使用 FormData 抓取我所有的输入文件来上传图像,但同时我想将会话 ID 附加到传递给服务器的信息中。一直以来,我认为通过附加信息,您将能够通过访问对象在服务器中看到它。我错了。当您附加到 FormData 时,在服务器上检查附加信息的方法是通过简单的$_POST['*your appended data*']查询。像这样:

js:

js:

$('form').submit(function(){
    var sessionID = 8;
    var formData = new FormData(this);
    formData.append('id', sessionID);

    $.ajax({
        url: "yoururl.php",
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data){
            alert(data);
        }
    });
});

then on php:

然后在 php 上:

$sessionID = $_POST['id'];
$files = $_FILES['image'];

$foreach ($files as $key=>val){
    //...
}

回答by madhu131313

If you are in Chrome you can check the Post Data

如果您在 Chrome 中,您可以检查发布数据

Here is How to check the Post data

这是如何检查邮政数据

  1. Go to Network Tab
  2. Look for the Link to which you are sending Post Data
  3. Click on it
  4. In the Headers, you can check Request Payload to check the post data
  1. 转到网络选项卡
  2. 查找您要将发布数据发送到的链接
  3. 点击它
  4. 在 Headers 中,您可以检查 Request Payload 以检查发布数据

Chrome's DevTools

Chrome 的开发者工具

回答by yehonatan yehezkel

you can see it you need to use console.log(formData.getAll('your key')); watch the https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll

你可以看到你需要使用它console.log(formData.getAll('your key'));观看 https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll

回答by Dulanga Heshan

form data doesn't appear in web browser console

表单数据未出现在 Web 浏览器控制台中

for (var data of formData) {
  console.log(data);
}

try this way it will show

试试这种方式它会显示

回答by Ramadanoski Julie

In my case on Edge browser:

就我在 Edge 浏览器上的情况而言:

  const formData = new FormData(this.form);
  for (const [key, value] of formData.entries()) {
      formObject[key] = value;
  }

give me the same error

给我同样的错误

So I'm not using FormDataand i just manually build an object

所以我没有使用FormData,我只是手动构建一个对象

import React from 'react';    
import formDataToObject from 'form-data-to-object';

  ...

let formObject = {};

// EDGE compatibility -  replace FormData by
for (let i = 0; i < this.form.length; i++) {
  if (this.form[i].name) {
    formObject[this.form[i].name] = this.form[i].value;
  }
}

const data = formDataToObject.toObj(formObject): // convert "user[email]":"[email protected]" => "user":{"email":"[email protected]"}

const orderRes = await fetch(`/api/orders`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });

const order = await orderRes.json();

回答by 7urkm3n

React Version

反应版本

Make sure to have a header with 'content-type': 'multipart/form-data'

确保有一个标题 'content-type': 'multipart/form-data'

_handleSubmit(e) {
    e.preventDefault();
    const formData = new FormData();
          formData.append('file', this.state.file);
    const config = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    }

     axios.post("/upload", formData, config)
         .then((resp) => {
             console.log(resp)
         }).catch((error) => {
    })
  }

  _handleImageChange(e) {
    e.preventDefault();
    let file = e.target.files[0];
    this.setState({
      file: file
    });
  }

View

看法

  #html
 <input className="form-control"
    type="file" 
    onChange={(e)=>this._handleImageChange(e)} 
 />