【问题标题】:Sending file data with ajax form submit使用ajax表单提交发送文件数据
【发布时间】:2016-04-19 11:41:59
【问题描述】:

我在使用 ajax 将文件发送到服务器进行提交时遇到问题。我用var xhr = new XMLHttpRequest();$.ajax({}); 尝试了很多方法,但总是给出错误Uncaught TypeError: Illegal invocation。我也使用processData: false,但在这种情况下,我得到了除了文件字段之外的所有表单字段。

我的 ajax 代码是:

var fd = new FormData();
fd.append( 'file', $('#file')[0].files[0] );
fd.append( 'name', 'test');
$.ajax({
    url: "uploadFile.php",
    data: fd,
    cache: false,
    contentType: false,
    // processData: false,
    type: 'POST',
    success: function(data, textStatus, jqXHR){
        console.log('success');
    },
    error: function(jqXHR, textStatus, errorThrown){
        console.log('error');
    }
});

在此我在输出中只得到了值为testname 字段,但没有file。 有人请让我知道我哪里错了。

【问题讨论】:

  • 需要表单代码,你是否添加了jquery库?
  • 你的数据中可能有fd.value
  • 我在我的html中添加了jquery库,我的html是<form method="post" action="" id="send" action="uploadFile.php" enctype="multipart/form-data"> <input type="text" name="email" /> <input type="file" name="file" id="file" /> <input type="submit" name="Submit" value="Submit" class="Submit"/> </form><script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  • 将字符串作为数据值。检查此链接stackoverflow.com/questions/10324594/jquery-illegal-invocation,如果您有任何问题,请告诉我

标签: javascript php jquery ajax forms


【解决方案1】:

将 contentType 设置为特定格式而不是 false。 例如。如果是图像,请将其设置为:- "image/jpeg" 等。

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多