将FormData转换为查询字符串的更简单方法

kle*_*und 11 javascript xmlhttprequest form-data

我正在通过XMLHttpRequest输入HTML表单的数据发送POST请求.不受JavaScript干扰的表单将提交其编码为的数据application/x-www-form-urlencoded.

使用XMLHttpRequest,我想通过FormDataAPI 发送数据,这不起作用,因为它将数据视为编码为multipart/form-data.因此,我需要将数据作为查询字符串,正确转义,写入到send方法中XMLHttpRequest.

addEntryForm.addEventListener('submit', function(event) {
    // Gather form data
    var formData = new FormData(this);
    // Array to store the stringified and encoded key-value-pairs.
    var parameters = []
    for (var pair of formData.entries()) {
        parameters.push(
            encodeURIComponent(pair[0]) + '=' +
            encodeURIComponent(pair[1])
        );
    }

    var httpRequest = new XMLHttpRequest();
    httpRequest.open(form.method, form.action);

    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.status === 200) {
                console.log('Successfully submitted the request');
            } else {
                console.log('Error while submitting the request');
            }
        }
    };

    httpRequest.send(parameters.join('&'));

    // Prevent submitting the form via regular request
    event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

现在for ... of循环等的整个事情看起来有点复杂.是否有更简单的方法转换FormData为查询字符串?或者我可以以某种方式发送FormData与不同的编码?

Han*_*ans 31

您可以使用URLSearchParams

const queryString = new URLSearchParams(new FormData(myForm)).toString()
Run Code Online (Sandbox Code Playgroud)

  • @otw 因为 `new URLSeachParams()` 返回一个对象,因此您需要将其转换为字符串才能使用它;) (3认同)
  • 好主意,除了当前的浏览器支持之外。https://caniuse.com/#feat=urlsearchparams (2认同)

And*_*eas 7

你问一个简单的解决方案......
一个for循环是遍历一个集合最简单的方法-恕我直言.

但是如果使用spread operator/syntax(),则会有一个较短的版本...

扩展语法允许在需要多个参数(用于函数调用)或多个元素(用于数组文字)或多个变量(用于解构赋值)的位置扩展表达式.

for...of然后您的循环可以替换为:

let parameters = [...formData.entries()] // expand the elements from the .entries() iterator into an actual array
                     .map(e => encodeURIComponent(e[0]) + "=" + encodeURIComponent(e[1]))  // transform the elements into encoded key-value-pairs
Run Code Online (Sandbox Code Playgroud)


Ale*_*dro 5

如果您可以使用JQuery,您只需.serialize()在您的form对象上调用函数,如下所示:

function getQueryString() {
  var str = $( "form" ).serialize();
  console.log(str);
}

$( "#cmdTest" ).on( "click", getQueryString );
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <select name="list1">
    <option>opt1</option>
    <option>opt2</option>
  </select>
 
  <br>
  <input type="text" name="txt1" value="valWith%Special&Char$">
  <br>
  <input type="checkbox" name="check" value="check1" id="ch1">
  <label for="ch1">check1</label>
  <input type="checkbox" name="check" value="check2" checked="checked" id="ch2">
  <label for="ch2">check2</label>
 
  <br>
  <input type="radio" name="radio" value="radio1" checked="checked" id="r1">
  <label for="r1">radio1</label>
  <input type="radio" name="radio" value="radio2" id="r2">
  <label for="r2">radio2</label>
</form>
  
<button id="cmdTest">Get queryString</button>
Run Code Online (Sandbox Code Playgroud)

注意:它还对数据进行编码以在 url 请求中使用它

希望对你有帮助,再见。