dsjk3214 2018-12-11 19:28
浏览 153
已采纳

FormData() - JQUERY

Until i needed to upload a file throw AJAX, i never knew there was a method like "FormData()" that POST all values of the FORM and some more.

I tested and worked perfect for file upload, but i could also send the other POST DATA, and this become even better.

Can i always use this for all my forms throw AJAX even if i don't have a file to upload? Or there is a downsizing of doing this other the upload the file?

In terms of performance, it's better to get the value of the input and send as data, or can i just use this to simplify?

The only information i could find about this, was for file upload, and not general use of this method.

Code Example:

<form id="theForm">
<<input id="test" type="text" name="test" placeholder="test" required="">
<input id="uploadFile" type="file" name="uploadFile" placeholder="uploadFile" required="">
<input id="submitFile" type="submit">
</form> 

$("#submitFile").on("click",function(event){

    event.preventDefault();

    var formData = new FormData($('#theForm')[0]);

    $.ajax({

            type: "POST",
            url: "inc/upload.php",
            data: formData,
            contentType: false,
            processData: false,
           beforeSend: function() {

               //Do Something 
         },

        })
        .done(function()
        {

        //Do Something 


        });


});

Thank you, Kind Regards!

  • 写回答

1条回答 默认 最新

  • dsyq40772 2018-12-11 20:20
    关注

    Yes, you can use FormData() for any form. The only downside is that it's a more verbose format. It uses the multipart/form-data encoding rather than application/x-www-form-urlencoded. Instead of the terse syntax:

    name1=value1&name2=value2&...
    

    the form parameters will be sent as something like:

    --Delimiter
    Content-Disposition: form-data; name="name1"
    
    value1
    --Delimiter
    Content-Disposition: form-data; name="name2"
    
    value2
    --Delimiter
    ...
    

    Where Delimiter is a long, random string.

    jQuery has a method $("#theForm").serialize() that will return the URL-encoded string. This can be used for any form that doesn't contain a file input.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型