POST文件数据,文本数据和可变数据通过Ajax到PHP文件进行上传

时间:2017-07-30 13:22:17

标签: php jquery ajax

我有三种类型的输入,分别是文件输入,文本输入和变量。我想通过使用Ajax JSON将数据发送到PHP文件来上传这些输入。另外,我想知道如何在PHP文件中捕获这些数据。

我使用的是没有表单语法的HTML代码。可变数据名称作为JQuery代码中的val1。

HTML代码:

<div class="container" id="post">
    <textarea id="posttext" autocomplete="off"></textarea>
    <input type="file" name="file" id="file" multiple accept=".mp4, .mov, .m4v, .MPEG-4, .gif, .jpg, .png"/>
    <button type="button" id="submitpost">Submit</button>
</div>

JQuery代码:

$(document).on("click", "#submitpost", function(){
    var val1 = "Some Datas";

        $.ajax({
        url: post.php,
        type: 'POST',
        data: VALUES,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
        });
});

PHP代码:

<?php
if (!isset($_POST['VALUES']) && !empty($_POST['VALUES'])) {
        $params = $_POST['VALUES'];

}
?>

如何在PHP中获取每个值以上载文件并将文本和变量数据插入数据库。

1 个答案:

答案 0 :(得分:1)

使用此代码:

<强> HTML

<div class="container" id="post">
  <form enctype="multipart/form-data" method="POST" id="myform">
    <textarea id="posttext" name="posttext" autocomplete="off"></textarea>
    <input type="file" name="file" id="file" multiple accept=".mp4, .mov, .m4v, .MPEG-4, .gif, .jpg, .png"/>
    <button type="submit" name="submitpost" id="submitpost">Submit</button>
   </form>
</div>

<强> Jquery的:

$(document).on("click", "#submitpost", function(e){
    $("form#myform").submit();
});
$("form#myform").on('submit', function(e){
    e.preventDefault();
    var val1 = "Some Data";
    var file = this.files[0];
    var form = new FormData();
    form.append('file', file);
    form.append('val1', val1);
    form.append('posttext', $('#posttext').val());
    $.ajax({
        url : "post.php",
        type: "POST",
        cache: false,
        async: false,
        contentType: false,
        processData: false,
        data : form,
        success: function(response){
            alert(response);
        }
    });
});

PHP代码:

<?php
if (isset($_POST) && !empty($_POST)) {
    print_r($_POST);
    print_r($_FILES);
}
?>