jQuery文件上传插件无法正常工作

时间:2015-05-05 16:29:59

标签: jquery ajax

我正在使用jQuery文件上传插件。在这里,我尝试更新现有图像:

$(document).ready(function() { 
    var options = { 
        target: '#notification_img',   // target element(s) to be updated with server response 
        beforeSubmit: beforeSubmit,  // pre-submit callback 
        success: afterSuccess,  // post-submit callback 
        resetForm: true        // reset the form after successful submit 
    };
    $('#MyImg').submit(function() {         
        $(this).ajaxSubmit(options);            
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    });

html表单

<form action="img_up.php" method="post" enctype="multipart/form-data"  id="MyImg">
        <label>Upload Photo</label><br>
        <input class="inp" id="photo-up" type="file" placeholder="Photo" name="photo-up"/><br/>
        <input class="btn" type="submit"  id="update-img-btn" value="Update" /><br/>
        <img src="images/ajax-loader.gif" id="loading-img" style="display:none; text-align:center;" alt="Please Wait"/>

   </form>

我的问题是,当我提交表单时,此页面会重定向到img_up.php文件。但这并不是因为我正在使用AJAX。图像未上传到目录中。我已经包含了所有必需的JavaScript文件。

3 个答案:

答案 0 :(得分:0)

使用此

更改您的功能
$('#update-img-btn').click(function(e) {
e.preventDefault();         
        $('#MyImg').ajaxSubmit(options);            
    //  // always return false to prevent standard browser submit and page navigation 
            return false; 
    });

要在目录中上传文件,您必须使用此代码

$sourcePath = $_FILES['photo-up']['tmp_name'];       // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['photo-up']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file

您可以在Google上搜索upload file using ajax php等教程,以下是您可以查看的几个链接

http://www.formget.com/ajax-image-upload-php/

http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

http://blog.teamtreehouse.com/uploading-files-ajax

答案 1 :(得分:0)

确保目标存在,否则将其加载到成功回调中的目标

var options = { 
    beforeSubmit: beforeSubmit,  // pre-submit callback 
    success: afterSuccess,  // post-submit callback 
    resetForm: true        // reset the form after successful submit 
};

$('#MyImg').submit(function() {         
    $(this).ajaxSubmit(options);            
    // always return false to prevent standard browser submit and page navigation 
    return false; 
});

function afterSuccess(responseText, statusText, xhr, $form)  { 
    $('#notification_img').html(responseText);
}

还要确保使用jquery正确加载javascript文件 你的代码看起来不错

答案 2 :(得分:-1)

从表单操作中删除img_up.php, 并将其添加到您的ajax:

...  
$('#MyImg').submit(function(event) {
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'img_up.php', // the url where we want to POST                
        })

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();