Plain Javascript Equivalent of jQuery.param()

后端 未结 7 1414
小蘑菇
小蘑菇 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:27

    You can also do that with pure JavaScript, but you have to write more lines of code. Try this:

    HTML code for testing:

    JavaScript to be fired onload:

    a = {
          userid:1,
          gender: "male",
        }
    
    url = Object.keys(a).map(function(k) {
        return encodeURIComponent(k) + '=' + encodeURIComponent(a[k])
    }).join('&')
    
    document.getElementById("test").innerHTML=url
    

    The output is this:

    userid=1&gender=male
    

    You can try this on JSFIDDLE.NET, it works, here's the link: http://jsfiddle.net/ert93wbp/

提交回复
热议问题