【问题标题】:Submitting image files with Ajax in PHP在 PHP 中使用 Ajax 提交图像文件
【发布时间】:2015-10-08 02:22:56
【问题描述】:

我对 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;
    });
});

【问题讨论】:

  • 序列化表单只编译值,它不会包含文件使用google学习如何使用ajax进行上传
  • 你可以在这里找到更好的方法stackoverflow.com/questions/4856917/…
  • @CallumBarclay:这个答案属于 2010 年
  • @charlietfl:感谢您的回答,我想知道对相同代码的任何修改是否可以让我通过表单推送我的文件。

标签: javascript php jquery html ajax


【解决方案1】:

这只是脚本的 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>

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多