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

后端 未结 2 1305
遇见更好的自我
遇见更好的自我 2021-01-02 12:04

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



        
相关标签:
2条回答
  • 2021-01-02 12:46

    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

    0 讨论(0)
  • 2021-01-02 12:57

    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);
    
    0 讨论(0)
提交回复
热议问题