new FormData() “application/x-www-form-urlencoded”

后端 未结 3 1662
独厮守ぢ
独厮守ぢ 2020-12-06 01:43

Couchdb only parse application/x-www-form-urlencoded. Is there a FormData() attribute that set the enctype?

xhr.open(\'put\',document.myForm.action,false)
xh         


        
3条回答
  •  攒了一身酷
    2020-12-06 02:43

    FormData will always be sent as multipart/form-data.

    If you want to send FormData as x-www-form-urlencoded, encode the content items:

    function urlencodeFormData(fd){
        var s = '';
        function encode(s){ return encodeURIComponent(s).replace(/%20/g,'+'); }
        for(var pair of fd.entries()){
            if(typeof pair[1]=='string'){
                s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
            }
        }
        return s;
    }
    
    var form = document.myForm;
    xhr.open('POST', form.action, false);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
    xhr.send(urlencodeFormData(new FormData(form)));
    

    you can also use URLSearchParams like this:

    function urlencodeFormData(fd){
        var params = new URLSearchParams();
        for(var pair of fd.entries()){
            typeof pair[1]=='string' && params.append(pair[0], pair[1]);
        }
        return params.toString();
    }
    

    For old browsers which doesn't support URLSearchParams API, you can use one of polyfills:

    • ethanius / URLSearchParams
    • WebReflection / url-search-params

提交回复
热议问题