php + ajax文件上传器,无法从POST获取数据

时间:2011-01-26 23:31:35

标签: php jquery

所以html代码我有:

<form id="loginIMGForm">            
<input type="file" name="file" id="loginIMG" />
<br />
<input type="submit" name="submit" value="Submit" id="submitloginIMG" />
</form>

<div id="loginIMGStatus">Select an image and upload.</div>

然后我有PHP代码:

<?php

$imageinfo = getimagesize($_FILES['loginIMGForm']['tmp_name']);

if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg') {
    echo "Sorry, we only accept GIF and JPEG images\n";
    exit;
}

$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['loginIMGForm']['name']);

if (move_uploaded_file($_FILES['loginIMGForm']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "File uploading failed.\n";
}
?>

和jquery是:

    $('#loginIMGForm').submit(function() {
        // 'this' refers to the current submitted form
        var str = $(this).serialize();
        alert(str);
        $.ajax({
            type: "POST",
            url: "modules/upload.php",
            data: str,
            success: function(msg){
                $("#loginIMGStatus").ajaxComplete(function(event, request, settings){
                    if(msg == 'OK'){ result = 'Login Image is updated'; }
                    else{ result = msg; }

                    $(this).html(result);
                });

            }

        });

        return false;
    }); 

I did debuging using alert, the data is empty. What did I do wrong.

感谢。

1 个答案:

答案 0 :(得分:0)

你为什么打电话给ajaxComplete

请改为:

$.ajax({
        type: "POST",
        url: "modules/upload.php",
        data: str,
        success: function(msg){
           var result;
           if(msg == 'OK'){ result = 'Login Image is updated'; }
                else{ result = msg; }

                $(this).html(result);
            });

        }

    });

此外,当您说数据为空时,您的意思是当您致电alerthtml组件时?

修改您无法在serialize上使用file。它不受支持,也没有意义。见this page。此外,虽然它还不是问题,但我怀疑你在调用ajaxComplete时会遇到问题。 {j}请求完成后,success参数已处理调用函数。我不确定你的代码会发生什么。