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

标签 javascript php jquery html ajax

我对 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>

关于javascript - 在 PHP 中使用 Ajax 提交图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491484/

相关文章:

javascript - SVG 文本路径动画 : treat path as circle?

javascript - 确保组件的客户端库文件仅在组件存在时加载到页面上的最佳方法是什么?

php - 在 MySQL 中执行 UNION ALL 时设置值

php - 在 php 中从数据库填充的下拉列表中设置选定的值

显示 :none attribute 的 jQuery 计数 div

javascript - 如何使用 jQuery/JavaScript 将每个字符添加到表单字段中

javascript - 两个小书签和一个 Greasemonkey 脚本可以组合成一个小书签吗?如果是这样,如何?

php - 确认设置提交按钮后提交 Jquery 表单

php - 我如何将自定义消息设置为此脚本的 sql 查询

jquery - css 图像过滤器 - 浏览器兼容性