在PHP中使用Ajax提交图像文件


Submitting image files with Ajax in PHP

我是Ajax和PHP的新手。我使用下面的代码通过Ajax提交我的HTML表单,但图像文件没有通过。我试着在代码中添加contentType仍然没有运气。请帮助我可以使用相同的代码(调整)提交图像文件连同文本输入?

代码如下:

$(document).ready(function() {
    $("#submit_form").submit(function() {       
        $.ajax({
            type: "POST",
            url: 'inc/submit_form.php',
            data:$("#submit_form").serialize(),
            success: function (data) {  
                // Inserting html into the result div on success
                $('#form-result').html(data);
            },
            error: function(jqXHR, text, error){
            // Displaying if there are any errors
                $('#form-result').html(error);           
        }
    });
        return false;
    });
});

这只是脚本的AJAX部分,但这是我过去使用的。我注释了每一行作为解释:

<script type="text/javascript">
var files = $('#TARGET_TO_FILES_INPUT').prop('files');
var data = new FormData();
$.each(files, function(key,val){
    data.append(key,val);
});

$.ajax({
    type:"POST",// post method
    url:UPLOAD_FILE,// path to file upload
    data:data,// image and any other form data
    cache:false,// stop any caching of browser
    dataType:'json',// return json when complete
    processData:false,// stop preprocessing of data by jquery (ie querystring)
    contentType:false,// must be set to false; turns off default "application/x-www-form-urlencoded; charset=UTF-8"
    success:function(o){
        // successful upload stuff goes here
    },
    xhr:function(){
        var xhr = $.ajaxSettings.xhr() ;
        xhr.upload.onprogress = function(evt){ 
            //progress bar stuff goes here
        }
        xhr.upload.onload = function(){
            //just before upload stuff goes here
        }
        return xhr ;
    }
});
</script>