如何上传阿贾克斯后连载上传、阿贾克斯后

2023-09-10 22:11:15 作者:国民渣男@

我有形式上传:

 <form method="post" id="edit_form" onsubmit="return edit(this.id);" enctype="multipart/form-data">
    <input type="file" name="thumb" />
    <input type="submit" value="Upload" />
</form>

和javascript函数:

and javascript function:

function edit(id){
    httplocal = location.href;
    var jqxhr = $.post(httplocal,$("#"+id).serialize(), function(data) {
        if(data.status == 1){
            $("#success").show();
        }else {
            $("#error").show();
        }
    }, "json")
    return false;
}

在PHP我检查:

in php i check :

if ($_FILES['thumb']['error'] != UPLOAD_ERR_NO_FILE) {
    code upload here...
}

但形式是空的 $ _ FILES ['大拇指'] 。对不起我的英语水平。

but form is empty $_FILES['thumb'] is null. Sorry my english.

推荐答案

您不需要的形式序列化。相反,你应该送 FORMDATA 类的一个实例。

You don't need to serialize the form. Instead you should send an instance of the FormData class.

        $("form").submit(function(event) {
            event.preventDefault();

            var data = new FormData($(this)[0]);

            $.ajax({
                // Note: to access both $_POST and $_FILES you should set these to false
                processData : false,
                contentType : false,

                url : "/php-script.php",
                data : data,
                success : function(response){
                    console.log(response);
                }
            });
        });

这是一个很常见的技术使用jQuery通过AJAX发送文件。

That's a very common technique to send files via AJAX using jquery.

 
精彩推荐
图片推荐