Jquery/Ajax 表单提交 (enctype="multipart/form-data" )。为什么“contentType:False”会导致 PHP 中的索引未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20795449/
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-08-25 03:34:19  来源:igfitidea点击:

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

phpajaxformsjquery

提问by DVCITIS

I have been trying to submit a form with enctype="multipart/form-data". I have this setting because the form will involve jpeg/png uploads once I have figured out the ajax submission for text inputs.

我一直在尝试提交一个带有 enctype="multipart/form-data" 的表单。我有这个设置,因为一旦我弄清楚了文本输入的 ajax 提交,表单将涉及 jpeg/png 上传。

  1. the php works fine when referencing the script using action within the form html.

  2. the form data seems to be retrieved correctly by the below jquery because the alert line shows: productName=Test+Name&productDescription=Test+Description&OtherProductDetails=

  3. the returned data printed to my HTML by the jquery success function is a php error saying:Undefined index: productName

  4. removing contentType:false fixes the problem.

  1. 使用表单 html 中的操作引用脚本时,php 工作正常。

  2. 以下 jquery 似乎正确检索了表单数据,因为警报行显示:productName=Test+Name&productDescription=Test+Description&OtherProductDetails=

  3. jquery成功函数打印到我的HTML的返回数据是一个php错误说:未定义索引:productName

  4. 删除 contentType:false 解决了这个问题。

When i google jquery/ajax multipart/form-data submission, the top hits at least mainly include 'contentType:false'. Please could someone explain the reason to me?

当我 google jquery/ajax multipart/form-data 提交时,最热门的至少主要包括“contentType:false”。请有人可以向我解释原因吗?

http://digipiph.com/blog/submitting-multipartform-data-using-jquery-and-ajaxhttp://hayageek.com/jquery-ajax-form-submit/Sending multipart/formdata with jQuery.ajax

http://digipiph.com/blog/submitting-multipartform-data-using-jquery-and-ajax http://hayageek.com/jquery-ajax-form-submit/使用 jQuery.ajax 发送 multipart/formdata

The jquery API documentation says: contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') Type: String When sending data to the server, use this content type.

jquery API 文档说: contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') Type: String 当向服务器发送数据时,使用此内容类型。

Why would we need to set it to false for a multipart/form-data submission? When would the false setting be needed at all?

为什么我们需要为 multipart/form-data 提交将其设置为 false?什么时候需要 false 设置?

Jquery:

查询:

  $("#addProductForm").submit(function (event) {
      event.preventDefault();
      //grab all form data  
      var formData = $(this).serialize();

      $.ajax({
          url: 'addProduct.php',
          type: 'POST',
          data: formData,
          async: false,
          cache: false,
          contentType: false,
          processData: false,
          success: function (returndata) {
              $("#productFormOutput").html(returndata);
              alert(formData);
          },
          error: function () {
              alert("error in ajax form submission");
          }
      });

      return false;
  });

回答by Dustin Cochran

contentTypeoption to falseis used for multipart/form-dataforms that pass files.

contentType选项false用于multipart/form-data传递文件的表单。

When one sets the contentTypeoption to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processDataflag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

当将该contentType选项设置为 时false,它会强制 jQuery 不添加 Content-Type 标头,否则,它将丢失边界字符串。此外,当通过 multipart/form-data 提交文件时,必须将该processData标志设置为 false,否则 jQuery 会尝试将您的 FormData 转换为字符串,这将失败。



要尝试解决您的问题:

Use jQuery's .serialize()method which creates a text string in standard URL-encoded notation.

使用 jQuery 的.serialize()方法以标准 URL 编码表示法创建文本字符串。

You need to pass un-encoded data when using contentType: false.

使用时需要传递未编码的数据contentType: false

Try using new FormDatainstead of .serialize():

尝试使用new FormData代替.serialize():

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

See for yourself the difference of how your formData is passed to your php page by using console.log().

亲眼看看您的 formData 如何通过使用console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

回答by Dhaval Bharadva

Please set your form action attributeas below it will solve your problem.

请设置您的表单操作属性如下,它将解决您的问题。

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

jQuery代码:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        event.preventDefault();
        //grab all form data  
        var formData = $(this).serialize();

        $.ajax({
            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });
});