【问题标题】:how did i can send form data with $.post()? [closed]我如何使用 $.post() 发送表单数据? [关闭]
【发布时间】:2020-02-22 09:22:03
【问题描述】:

我可以使用 $.ajax 为上传的文件发送 form_data。但是当我使用 (input: file) 时,如何使用 $.post() 将表单数据作为图像文件选择输入到 PHP 中?

<input type="file" id="img" name="img" accept="image/jpg,image/jpeg" style="display: none">

【问题讨论】:

  • 请查看link发布文件数据
  • 该链接使用 $ajax,我想要 $.post() 方法。 @MNJ
  • $.post() 只是$.ajax({ method: "post", ... })的简写
  • @Andreas 谢谢我知道,但我不知道如何用 $.post() 方法编写!!!

标签: javascript php jquery html post


【解决方案1】:

你需要制作POSTenctype="multipart/form-data"形式的方法

<form method="POST" action="URL" enctype="multipart/form-data">
<input type="file" id="img" name="img" accept="image/jpg,image/jpeg" style="display: none">
</form>

然后您可以将上传的图片作为$_FILES 获取表单发布的位置。

【讨论】:

  • 感谢您的回答,但是我如何在没有表单标签、jquery 和 post() 方法的情况下编写? :)
【解决方案2】:
<input type="file" id="img" name="img" accept="image/jpg,image/jpeg">

您需要通过onchange 事件获得file input

$(document).ready(function() {
    $('#img').change(function(){
        var file_data = $('#img').prop('files')[0];   
        var form_data = new FormData();                  
        form_data.append('file', file_data);
        $.ajax({
            url: "fileUpload.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                console.log(data);
            }
        });
    });
});

【讨论】:

  • "但是我需要 $.post()" 评论在 3, 2, 1, ...
  • $.post() 方法只是 $.ajax() 与 POST 方法的简写,当您谈论 formdate 或图像上传时,它会像这样工作。
  • 这就是我在他的问题下方的 cmets 中告诉 OP 的内容。还没有用^^
  • 当我写 $.post('file.php', { data: data }, function(data){ } ) 我不能写这个树选项: ((contentType: false, cache: false, processData:false)) 我不知道怎么写
猜你喜欢
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
相关资源
最近更新 更多