javascript 通过ajax的javascript表单数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9099486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:35:44  来源:igfitidea点击:

javascript formdata via ajax

javascriptjquery

提问by DG3

I am trying to upload a file via AJAX and PHP. I have a HTML form as below:

我正在尝试通过 AJAX 和 PHP 上传文件。我有一个 HTML 表单,如下所示:

<form method="post" id="sectiononeform" name="sectiononeform" enctype="multipart/form-data">

    <div class="clearfix">
        <input type="text" name="customHeading1" id="customHeading1" class="span10" value=""/>
    </div>

    <!-- Gets replaced with TinyMCE, remember HTML in a textarea should be encoded -->
    <div class="clearfix">
        <textarea id="elm1" name="elm1" rows="15" class="xxlarge" cols="80" style="width: 80%">

        </textarea>
    </div>

    <div class="clearfix">
        <input type="file" name="file1" id="file1" class="span10" />
    </div>

    <div class="clearfix">        
        <div class="actions">
            <input type="submit" id="saveSection1" name="saveSection1" value="Submit" />
            <input type="reset" name="resetSection1" value="Reset" />                
        </div>
    </div>

</form>

My jquery code is as follows:

我的jquery代码如下:

$(document).ready(function(){
    $("#saveSection1").click(function(e){
        e.preventDefault();

        var formdata = false;

        /*function showUploadedItem (source) {
            var list = document.getElementById("image-list"),
                li   = document.createElement("li"),
                img  = document.createElement("img");
            img.src = source;
            li.appendChild(img);
            list.appendChild(li);
        }   */

        if (window.FormData) {
            formdata = new FormData();

            //document.getElementById("btn").style.display = "none";
        }

        var len = document.getElementById("file1").files.length, img, reader, file;

        for (var i = 0 ; i < len; i++ ) {
            file = document.getElementById("file1").files[i];
            if (!!file.type.match(/image.*/)) {
                if (window.FileReader ) {
                    reader = new FileReader();
                    /*reader.onloadend = function (e) { 
                        showUploadedItem(e.target.result, file.fileName);
                    };*/
                    reader.readAsDataURL(file);
                }
                if (formdata) {
                    alert("form data");
                    formdata.append("customHeading1", document.getElementById("customHeading1").value);
                    formdata.append("elm1", document.getElementById("elm1").value);
                    formdata.append("custsection1", 1);
                    formdata.append("venue_id", document.getElementById("venue_id").value);
                    formdata.append("images[]", file);
                    alert(formdata);
                }
            }   
        } 
        var params = $("form#sectiononeform").serialize();
        //alert("params" + params);
        params = params + "&custsection1=1&venue_id=" + $("#venue_id").val() + "&formdata=" + formdata;
        //alert(params);
        $.ajax({
          type: 'POST',
          url: 'saveCustomSectionData.php',
          data: formdata,
          success: function(data){
            alert(data);
          }
        });
    });
});

My issue is that when I don't use the file input type, I can just serialize the form values and send it through AJAX. Since I am using file input type, I am using formdata and appending information to it. Is this the right way to send data. I am not getting any response back from php, neither can i see any request in firebug. Instead I get some vague error as "Illegal operation on WrappedNative prototype object". Any suggestions?

我的问题是,当我不使用文件输入类型时,我可以序列化表单值并通过 AJAX 发送它。由于我使用的是文件输入类型,因此我使用的是 formdata 并向其附加信息。这是发送数据的正确方式吗?我没有从 php 得到任何响应,我也看不到 firebug 中的任何请求。相反,我得到了一些模糊的错误,如“对 WrappedNative 原型对象的非法操作”。有什么建议?

回答by Rafael Veiga Cid

You can use AJAX to send files. Using new FormData() and the $.ajax method with contentType: false, processData: false.

您可以使用 AJAX 发送文件。使用 new FormData() 和 $.ajax 方法与 contentType: false, processData: false。

Check this out:

看一下这个:

<script type="text/javascript">
$(document).ready(function()
{
    $("#ajax").hide();

    $("#botonancho").click(function()
    {
        if ($("#ficherocsv").val() =="")
        {
            alert("   Seleccione 1o el archivo ");  
        }
        else
        {
            var data = new FormData();
            data.append( 'file', $( '#ficherocsv' )[0].files[0] );

            $("#botonancho").val("Por favor... espere.");
            $("#ajax").html("<img src='imagenes/ajax-indicator.gif' alt='Indicador Actividade Ajax' />").show();

            $.ajax({
                url: 'importacion.php',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data)
                {
                    $("#ajax").html("");

                    $("#ajax").html(data).fadeIn("slow",function()
                    {
                        $("#ajax").delay(1500).fadeOut("slow",function()
                        {
                            $("#botonancho").val("IMPORTAR Alumnos CSV (codificación UTF-8)");
                            $("#ficherocsv").val("");
                            $("#ajax").hide();

                        });
                    });
                }
            }); 
        }
    });

});
</script>

Regards.

问候。

回答by Qpirate

so far as i know this is not possible due to security reasons.

据我所知,由于安全原因,这是不可能的。

but it is possible to use something like jquery.form.js (available from http://jquery.malsup.com/form/) and is quite easy to implement.

但是可以使用类似 jquery.form.js(可从http://jquery.malsup.com/form/ 获得)的东西,并且很容易实现。

they do also provide some nice examples for you to try aswel.

他们还提供了一些很好的例子供您尝试 aswel。