Ajax表单提交附件 [英] Ajax Form Submit with attachment

查看:173
本文介绍了Ajax表单提交附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一个提交了真实Ajax的表格.该表格有一个附加.pdf文件的字段.尽管文件未与其余数据一起发送,但提交表单时的方式.

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.

我该如何使用它? 这是我的Ajax代码:

How can i get this to work? Here is my ajax code:

$('#submit_btn').click(function () {
                $.ajax({
                    type: 'POST',
                    url: '/contact.php',
                    dataType: "json",
                    data: $('#contactform').serialize(),
                    success: function (data) {

                        console.log(data.type);
                        console.log(data.msg);

                        var nClass = data.type;
                        var nTxt = data.msg;

                        $("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
                        //reset fields if success
                        if (nClass != 'danger') {
                            $('#contactform input').val('');
                            $('#contactform textarea').val('');
                        }

                    }
                });
                return false;
            });

在php端,我有phpmailer设置并正在处理文件,因此:

On the php side i have phpmailer setup and am handling the file so:

if(!empty($_FILES['file'])) {
            $_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']); 
        }  

推荐答案

        $('#submit_btn').click(function () {
                    var formData = new FormData($('#contactform'));
                        $.ajax({
                            type: 'POST',
                            url: '/contact.php',
                           // dataType: "json",
                            data: formData ,
                      processData: false,
                        contentType: false,
                            success: function (data) {

                                console.log(data.type);
                                console.log(data.msg);

                                var nClass = data.type;
                                var nTxt = data.msg;

                                $("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
                                //reset fields if success
                                if (nClass != 'danger') {
                                    $('#contactform input').val('');
                                    $('#contactform textarea').val('');
                                }

                            }
                        });
                        return false;
                    });

这篇关于Ajax表单提交附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆