我的Javascript和PHP通信之间有什么问题,用于上传图像


What's wrong between my Javascript and PHP communication for uploading an image?

我被要求只使用Javascript(Ajax/Jquery/JSON)。为什么这不起作用?

这是我嵌入在 HTML 脚本中的代码:

function uploadImage(){
    $.post("signup/upload.php", function(data)
    {
        if(data['status']!='ok'){
          $("#status").html(data['status']);
          console.log("!Failure");
        }else{
          $('#status').html("Your picture was uploaded!");
          console.log("Success");
        }
    });
}
$(document).ready(function () {
    $('#uploadImageButton').on('click', function()
    {
        uploadImage();
    });
});

这是 HTML:

<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Submit" id = "uploadImageButton" name="submit">

这是 PHP:

  $reply['status'] = 'ok';
    <?php
    if(isset($_POST['submit'])) {
            if (isset($_FILES['upload'])) {
                    $allowed = array ('image/pjpeg', 'image/jpeg','image/JPG');
                    if (in_array($_FILES['upload']['type'], $allowed)) {
                            if (move_uploaded_file
                                    ($_FILES['upload']['tmp_name'], "/fakepath/www/upload_files/{$_FILES['upload']['name']}"))
                            {
                                    $reply['status'] = 'ok';
                                    echo '<p><em>The file has been uploaded!</em></p>';
                            }
                    } else {
                            echo '<p class="error">Please upload a JPEG or PNG image.</p>';
                    }
        }
}
print json_encode($reply);
?>

你应该使用$.ajax请求,例如下面。

.HTML:

<form enctype="multipart/form-data">
    <input type="file" name="upload" id="fileToUpload">
    <input type="submit" value="Submit" id = "uploadImageButton" name="submit">
<form>

.JS:

$(function(){
    $('body').on('submit', 'form', function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "signup/upload.php",
            data: new FormData(this),
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                //your code
            }
        });
        return false;
    })  
})

希望这有帮助。

第一个PHP指令$reply['status'] = 'ok';不会执行,因为它被放置在PHP打开标签之前。