【问题标题】:Var dump formdata as POST returns NULLVar dump formdata as POST 返回 NULL
【发布时间】:2017-11-07 11:53:19
【问题描述】:

我看到了一些使用 formdata 通过 ajax 上传图像的简单代码,但在 php 端,它在 $_POST 内显示为 NULL,我尝试使用 echo $_POST['file']['name'],但它没有任何回应...

我的 php 文件有:

var_dump($_POST);

如何使用ajax发送给php的formData(在php中)?

$(document).on('change','#image',function(){
    var fd = new FormData();    
        fd.append( 'file', $(this).prop("files")[0]);
       console.log(fd);
    $.ajax({
        type: 'post',
        processData: false,
        contentType: false,
        url: './images.php',
        data: fd,
        success: function(a){
            console.log(a);
        }
    });
 });
#image{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<label for="image"><i class="fa fa-camera" aria-hidden="true"></i></label><input  type="file" name="file" id="image">

【问题讨论】:

  • 你的表格在哪里?
  • 我在不需要表格的地方读到了。
  • 你的意思是 $_FILES 而不是 $_POST
  • $_FILES['file']['tmp_name']
  • $_FILES['file']['name']

标签: javascript php jquery ajax


【解决方案1】:

你必须使用超全局$_FILES而不是$_POST试试:

var_dump($_FILES);

输出类似:

 array (size=1)  'file' =>
      array (size=5)
            'name' => string '49e9c80947764261bbd9d46a8063c3d1.jpg' (length=36)      
            'type' => string 'image/jpeg' (length=10)
            'tmp_name' => string 'C:\xampp\tmp\php64A9.tmp' (length=24)      
            'error' => int 0
            'size' => int 3090

【讨论】:

  • 也试过了,结果一样:/
  • @StupidKid 我使用了你的代码来检查它并且它有效。您如何检查$_POST$_FILES 是否为空?
  • 使用开发工具的Network 选项卡进行确认。
  • 好吧,这可能是我的错,但我使用了 var_dump() 并且 ajax 成功后它在 console.log 中返回 NULL,或者当我尝试回显某些内容并在 ajax 成功中将其作为文本返回时,它返回空。
  • 哦,我没想到,嗯,我接受了你的回答,虽然我试过了,但没用,现在可以了:D
【解决方案2】:

这对我有用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<form id="imageUpload">
    <label for="image"><i class="fa fa-camera" aria-hidden="true"></i></label><input  type="file" name="file" id="image">
</form>
<script type="text/javascript">
    $(document).on('change','#image',function(){

    var fd = new FormData($("#imageUpload")[0]);
        fd.append('file',$(this)[0].files[0]);

       console.log(fd);
    $.ajax({
        type: 'post',
        processData: false,
        contentType: false,
        url: 'testimage.php',//change to yours
        data: fd,
        success: function(a){
            console.log(a);
        }
    });
    });

</script>

然后是我的php

<?php

    var_dump($_FILES);

结果:

【讨论】:

    猜你喜欢
    • 2022-06-11
    • 1970-01-01
    • 2023-03-20
    • 2012-05-04
    • 1970-01-01
    • 2015-11-27
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多