Easier way to transform FormData into query string

前端 未结 3 1201
渐次进展
渐次进展 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
    
    0 讨论(0)
  • 2021-02-02 09:44

    You could use URLSearchParams

    const queryString = new URLSearchParams(new FormData(myForm)).toString()
    
    0 讨论(0)
  • 2021-02-02 09:46

    If you could use JQuery, you'll simply call .serialize() function on your form object, like follow:

    function getQueryString() {
      var str = $( "form" ).serialize();
      console.log(str);
    }
    
    $( "#cmdTest" ).on( "click", getQueryString );
    <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>

    Note: It also encode data for use it in url request

    I hope it helps you, bye.

    0 讨论(0)
提交回复
热议问题