formData get() Doesn't seem to work in Safari

2020-02-28 09:01发布

This is my code. It works in Firefox and Chrome but not Safari. I get no errors.

<script>
var cleanData = new FormData();
cleanData.append("test", "test");
alert(cleanData.get("test"));
</script>

Does anyone know a workaround?

标签: safari
2条回答
Explosion°爆炸
2楼-- · 2020-02-28 09:24

I solved this by conditionally (if Safari is the browser) iterating through the elements property of an actual form. For all other browser, my wrapper just iterates through FormData entries(). The end result of my function, in either case, is a simple javascript object (JSON) which amounts to name/value pairs.

function FormDataNameValuePairs(FormName)
{
  var FormDaytaObject={};
  var FormElement=$('#'+FormName).get(0);

  if (IsSafariBrowser())
  {
    var FormElementCollection=FormElement.elements;
    //console.log('namedItem='+FormElementCollection.namedItem('KEY'));
    var JQEle,EleType;
    for (ele=0; (ele < FormElementCollection.length); ele++)
    {
      JQEle=$(FormElementCollection.item(ele));
      EleType=JQEle.attr('type');

      // https://github.com/jimmywarting/FormData/blob/master/FormData.js
      if ((! JQEle.attr('name')) ||
          (((EleType == 'checkbox') || (EleType == 'radio')) &&
           (! JQEle.prop('checked'))))
        continue;
      FormDaytaObject[JQEle.attr('name')]=JQEle.val();
    }
  }
  else
  {
    var FormDayta=new FormData(FormElement);
    for (var fld of FormDayta.entries())
      FormDaytaObject[fld[0]]=fld[1];
  }

  return FormDaytaObject;
}

where IsSafariBrowser() is implemented by whatever your favorite method is, but I chose this:

function IsSafariBrowser()
{
  var VendorName=window.navigator.vendor;
  return ((VendorName.indexOf('Apple') > -1) &&
          (window.navigator.userAgent.indexOf('Safari') > -1));
}

Example usage in OP's case, assuming that you have an actual form called CleanDataForm instead of creating a FormData from scratch:

var cleanData=FormDataNameValuePairs('CleanDataForm');
alert(cleanData.test);
查看更多
一夜七次
3楼-- · 2020-02-28 09:28

Apparently, Safari has no means of getting values stored in FormData objects at this time. There is no workaround at this time, and apparently it's not practical to polyfill.

Sorry :(

Notes: https://developer.mozilla.org/en-US/docs/Web/API/FormData/get#Browser_compatibility https://www.bountysource.com/issues/27573236-is-it-possible-to-polyfill-missing-formdata-methods

查看更多
登录 后发表回答