Easier way to transform FormData into query string

前端 未结 3 1203
渐次进展
渐次进展 2021-02-02 09:26

I’m sending a POST request via XMLHttpRequest with data entered into an HTML form. The form without interference of JavaScript would submit its data encoded as

3条回答
  •  被撕碎了的回忆
    2021-02-02 09:42

    You've asked for a simpler solution...
    A for loop is the simplest way to traverse over a collection - imho.

    But there is a shorter version if you use the spread operator/syntax (...)

    The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

    Your for...of loop can then be replaced with:

    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
    

提交回复
热议问题