【问题标题】:problem of Multipart/form-data with PHP and AJAX by POST method [duplicate]POST方法使用PHP和AJAX的Multipart / form-data问题[重复]
【发布时间】:2020-12-23 08:57:33
【问题描述】:

我在 PHP 中创建了一个表单,以便在我的数据库中插入表单中的图像。表单有效,我的 Ajax 请求也有效。问题是当我想在'../uploads' 存储库中插入我的图像时,我必须使用$_FILES 方法,而当我的ajax 请求不再工作时......我不明白,我创建了另一个表单只是为了测试我在存储库中插入图像的 php 代码是否正确。 我做了研究,我认为它可以链接到 ajax 中的multipart/form-data(我对 AJAX 了解不多,真的)。 有人能帮助我吗 ? 这是我的代码:

形式:

<form action="traitement.php" method="post" enctype="multipart/form-data" id="form_img">
   Choose a file<input type="file" name="fileToUpload" id="fileToUpload">
   <button type="submit" name="submit_btn" id="submit_btn">OKK</button>
</form>

php 的特点:

$target_dir = "../uploads/";
$target_file = $target_dir.basename($_POST['fileToUpload']);
//$exec is my sql request to insert the image (and it works).
if ($exec){ 
                echo "Success";
                move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
            }

我的 ajax 请求:

$("#form_img").submit(function(e){
            e.preventDefault();
    
            $.post(
                'traitement.php', 
                {
                    fileToUpload : $("#fileToUpload").val()                    },
    
                function(data){
                    if(data == 'Success'){
                     $("#text_ajt").removeClass('text-warning').addClass('text-success').html("cool");
                    }
                    if(data == 'Failed'){
                        $("#text_ajt").addClass('text-danger').html("respect the format");
                    }
                    if(data == 'Miss'){
                        $("#text_ajt").addClass('text-warning').html("miss something");
                    }
                },
                'text'
            );
        });

【问题讨论】:

  • 你想用ajax在php中插入什么图片??

标签: javascript php ajax forms image


【解决方案1】:

这里不需要 Ajax。 只需将您的表单(使用目标)发送到隐藏的 iframe 并为您的 iframe 编写加载事件。

类似这样的:

HTML:

<form action="traitement.php" method="post" enctype="multipart/form-data" target="file_upload_frame" id="form_img">
   Choose a file<input type="file" name="fileToUpload" id="fileToUpload">
   <button type="submit" name="submit_btn" id="submit_btn">OKK</button>
</form>

<iframe id="file_upload_frame" name="file_upload_frame" frameborder="0" style="display: none"></iframe>

jQuery:

$('#file_upload_frame').on("load", function () {
    var response = $(this).contents().find('body').html()
           
    alert(response );
});

【讨论】:

  • 您好,感谢您的回答。我尝试了你所做的,但它不起作用......我想我不明白 AJAX REQUEST 的工作方式。我注意到,当我在 php 中的“if”条件下只有“成功”的回声时,它可以工作。但是当我添加一些 php 代码时,它不再起作用了......它是否链接到数据 AJAX receveid ?我输入了“文本”,但我不知道是不是那个
猜你喜欢
  • 2011-04-22
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
  • 2015-09-19
  • 1970-01-01
相关资源
最近更新 更多