jQuery - FormData发送一个空图像

时间:2015-07-20 16:33:57

标签: jquery ajax

当我使用jquery提交表单时,发生了奇怪的事情。即使我没有选择表单中的任何图像,$_FILES数组也包含空值。如果我选择图像,则会有一个额外的空值。

以前是否有人见过这个?

Array
(
    [item_image] => Array
        (
            [name] => Array
                (
                    [0] => 
                )

            [type] => Array
                (
                    [0] => 
                )

            [tmp_name] => Array
                (
                    [0] => 
                )

            [error] => Array
                (
                    [0] => 4
                )

            [size] => Array
                (
                    [0] => 0
                )

        )

)
  

AJAX

$( "#fileupload" ).submit(function( event )
    {
        //disable the default form submission
        event.preventDefault();

        //grab all form data
        var formData = new FormData(this);

        $.ajax({
            url: 'ajax/add-item.php',
            data: formData,
            type: 'POST',
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                alert(data);
                if(data)
                {
                    $("#fileupload > div.alert").text('Upload successful.');
                    $('html, body').animate({scrollTop : 0},700);
                    document.getElementById("#fileupload").reset();
                }
            }
        });

    });

1 个答案:

答案 0 :(得分:1)

请尝试以下示例:

<强> HTML / PHP

<?
    print_r($_POST);
    print_r($_FILES);
?>

<form id="data" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button>Submit</button>
</form>

<强>的jQuery

$("form#data").submit(function(){

    var formData = new FormData($(this)[0]);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});
祝你好运!!