File value is undefined in jQuery click

huangapple go评论105阅读模式
英文:

File value is undefined in jQuery click

问题

以下是要翻译的内容:

在我的项目中,所有表单都相似,所以我想编写一个点击函数来运行它们。以下代码除了文件外都可以正常工作。文件值输出为 undefined。我该如何将文件附加到这个表单数据中?这是我的点击函数:

  1. $("#save_form").click(
  2. function(event){
  3. event.preventDefault();
  4. var formData = {};
  5. $('.form-value').each(function() {
  6. var id = $(this).attr('id');
  7. var value;
  8. if ($(this).is('select')) {
  9. value = $(this).find('option:selected').val();
  10. } else if ($(this).is(':file')) {
  11. value = $(this)[0].files[0].value; // 返回 undefined。
  12. } else {
  13. value = $(this).val();
  14. }
  15. formData[id] = value;
  16. });
  17. console.log(formData);

当我不使用 .value 时:

  1. value = $(this)[0].files[0]

我得到:

  1. Uncaught TypeError: Illegal invocation
英文:

In my project, all forms are similar to each other, so I want to write one click function to run all.

Following code works fine except files. File value outputs as undefined. How can I attach file to this form data?

Here's my click function:

  1. $("#save_form").click(
  2. function(event){
  3. event.preventDefault();
  4. var formData = {};
  5. $('.form-value').each(function() {
  6. var id = $(this).attr('id');
  7. var value;
  8. if ($(this).is('select')) {
  9. value = $(this).find('option:selected').val();
  10. } else if ($(this).is(':file')) {
  11. value = $(this)[0].files[0].value; // Returns undefined.
  12. } else {
  13. value = $(this).val();
  14. }
  15. formData[id] = value;
  16. });
  17. console.log(formData);

When I use without value:

  1. value = $(this)[0].files[0]

I get:

  1. Uncaught TypeError: Illegal invocation

答案1

得分: 3

只使用文件本身。文件没有value属性。

  1. value = this.files[0];

要使用jQuery.ajax发送FormData,请添加选项processData: falsecontentType: false,以防止jQuery尝试转换FormData

英文:

Just use the file itself. Files do not have a value property.

  1. value = this.files[0];

To send the FormData with jQuery.ajax, add the options processData: false and contentType: false to prevent jQuery from trying to convert the FormData.

答案2

得分: 2

借助David和Unmitigated的帮助,我解决了这个问题。

  • 我发送的是文件,而不是数值。

    1. value = $(this)[0].files[0];
  • 然后,我添加了两行到ajax(processData和contentType设置为false)

    1. method: 'POST',
    2. data: formData,
    3. processData: false,
    4. contentType: false,
英文:

With the help of David and Unmitigated, I solved the issue.

  • I send file, not the value.

    1. value = $(this)[0].files[0];
  • And than, I added two lines to ajax (processData and contentType as false)

    1. method: 'POST',
    2. data: formData,
    3. processData: false,
    4. contentType: false,

huangapple
  • 本文由 发表于 2023年8月4日 02:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定