FormData.append(“key”, “value”) is not working

随声附和 提交于 2019-12-17 03:49:38

问题


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 :/


回答1:


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

  • formdata.entries() (combine with Array.from() for debugability)
  • formdata.get(key)
  • and more very useful methods

Original answer:

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

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

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

Easy.




回答2:


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

There's no way of getting the data out of a FormData object; it's just intended for you to use to send data along with an XMLHttpRequest object (for the send method).

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




回答3:


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:

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:

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

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



回答4:


If you are in Chrome you can check the Post Data

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




回答5:


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




回答6:


form data doesn't appear in web browser console

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

try this way it will show




回答7:


In my case on Edge browser:

  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 FormData and i just manually build an object

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]":"customer@mail.com" => "user":{"email":"customer@mail.com"}

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



回答8:


React Version

Make sure to have a header with '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)} 
 />


来源:https://stackoverflow.com/questions/7752188/formdata-appendkey-value-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!