Plain Javascript Equivalent of jQuery.param()

后端 未结 7 1256
小蘑菇
小蘑菇 2021-02-07 11:04

jQuery.param() takes an array of key-value pairs, and turns it into a string you can use as a query string in HTML requests. For example,

a = {
      userid:1,
         


        
7条回答
  •  攒了一身酷
    2021-02-07 11:29

    This was a bit frustrating. None of the solutions here seemed to actually work to produce actual "x-www-form-urlencoded" data for any JSON object, the equivalent of JQuery. Some came close but failed on child items. I pieced code from a few of the solutions to get this, working version for any JSON object:

    function formData (obj) {
      return Object.keys(obj).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(JSON.stringify(obj[k]))).join('&')
    }
    

    FYI I had to use this for FastSpring's API, because for some freaky reason they only accept x-www-form-urlencoded data in 2020. Spent all day on this because this is the first time in almost a decade an API didn't just accept JSON :(

提交回复
热议问题