FormData.append(“key”, “value”) 不起作用

发布于 2024-12-09 08:53:48 字数 1350 浏览 0 评论 0原文

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

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

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

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] }

我无法理解!昨天还好好的,今天我的头却把键盘撞坏了很多次! Firefox、Chrome,两者都一样:/

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

轻许诺言 2024-12-16 08:53:49

如果您使用的是 Chrome,您可以检查帖子数据

以下是如何检查帖子数据

  1. 转至网络选项卡
  2. 查找您要发送帖子数据的链接
  3. 单击它
  4. 在标头中,您可以检查请求有效负载以检查帖子数据

Chrome 的开发工具

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

Chrome's DevTools

橘虞初梦 2024-12-16 08:53:49

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

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

尝试这种方式它会显示

form data doesn't appear in web browser console

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

try this way it will show

心如荒岛 2024-12-16 08:53:49

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

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

感性不性感 2024-12-16 08:53:49

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

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

给我同​​样的错误

所以我没有使用 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();

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]":"[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();
一生独一 2024-12-16 08:53:49

React 版本

确保标题带有 '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
    });
  }

查看

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

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)} 
 />
纸短情长 2024-12-16 08:53:48

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

  • formdata.entries() (与 Array.from() 结合使用)为了可调试性)
  • formdata.get(key)
  • 和更多非常有用的方法

原始答案:

我通常会做什么来“调试”FormData对象,只是发送它(任何地方!)并检查浏览器日志(例如 Chrome 开发工具的“网络”选项卡)。

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

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

简单。

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.

孤寂小茶 2024-12-16 08:53:48

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

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

近五年后更新:在一些较新的浏览器中,这不再是事实,除了将数据填充到其中之外,您现在还可以看到提供给 FormData 的数据。 查看已接受的答案了解更多信息。

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.

红玫瑰 2024-12-16 08:53:48

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

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

然后在php上:

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

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

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){
    //...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文