JS object to URL parameter (native JS and jquery two ways)

Source: Internet
Author: User
Tags urlencode

Turn from: Click to open link

Now the JS framework encapsulates the AJAX request very simply, such as the following:

[JavaScript] View plain copy
    1. $.ajax ({  
    2.          type: 
    3.          url:  "some.php",   
    4.          data: { name:  "John",  Location:  "Boston"  }  
    5.      }). Done (function ( msg )  {  
    6.          alert (  "data saved: "  +  msg );   
    7.     });   



Above is a piece of Ajax request code based on the jquery framework, using the POST request method
But in some scenarios we still have to use get mode, and we need to spell out the request parameters, such as window.open, the a tag's href, and so on. Code such as this concatenation of strings is prone to errors, such as stitching all properties and values of an object into a URL's request parameter. We may need this:

[JavaScript] View plain copy
    1. var params = ';
    2. params + = ' key1= ' +obj.key1;
    3. params + = ' key2= ' +obj.key2;
    4. params + = ' key3= ' +obj.key3;
    5. params + = ' key4= ' +obj.key4;
    6. ...



Needless to say too much, painful ah, like hard labor, a little can not understand the programmer on the tall feeling. Maybe we can.

[JavaScript] View plain copy
    1. var params = UrlEncode (obj);

In that case, how does this happen? Take a look at a buddy on the Internet implementation of jquery-based approach

[JavaScript] View plain copy
  1. var parseparam=function (param, key) {
  2. var paramstr="";
  3. if (param instanceof string| | param instanceof number| | param instanceof Boolean) {
  4. paramstr+="&" +key+ "=" +encodeuricomponent (param);
  5. }else{
  6. $.each (param,function (i) {
  7. var k=key==null?i:key+ (param instanceof Array?" ["+i+"] ":". "  +i);
  8. paramstr+=' & ' +parseparam (this, k);
  9. });
  10. }
  11. return Paramstr.substr (1);
  12. };

[JavaScript] View plain copy
    1. Test
    2. var obj={name:' Tom ',' class ': {className:' Class1 '},classmates:[{name:' Lily '}]};
    3. ParseParam (obj);
    4. Output: "Name=tom&class.classname=class1&classmates[0].name=lily"
    5. ParseParam (obj,' Stu ');
    6. Output: "Stu.name=tom&stu.class.classname=class1&stu.classmates[0].name=lily"



Reference from Liu Jiahua http://www.oschina.net/code/snippet_139242_7584


Since this code itself is not much, in order to enhance its versatility, I used native JavaScript to rewrite the method, as follows:

[JavaScript] View plain copy
  1. /**
  2. * Param the object that will be converted to the URL parameter string
  3. * Key URL parameter string prefix
  4. * Encode True/false is URL encoded, default is True
  5. *
  6. * Return URL parameter string
  7. */
  8. var UrlEncode = function (param, key, encode) {
  9. if (param==null) return ';
  10. var paramstr = ';
  11. var t = typeof (param);
  12. if (t = = ' string ' | | t = = ' number ' | | t = = ' Boolean ') {
  13. Paramstr + = ' & ' + key + ' = ' + ((encode==null| | Encode)?  encodeURIComponent (param): param);
  14. } Else {
  15. For (var i in param) {
  16. var k = key = = null? I:key + (param instanceof Array?)  ' [' + i + '] ': ' . ' + i);
  17. Paramstr + = UrlEncode (Param[i], k, encode);
  18. }
  19. }
  20. return paramstr;
  21. };
  22. var obj={name:' Tom ',' class ': {className:' Class1 '},classmates:[{name:' Lily '}]};
  23. Console.log (UrlEncode (obj));
  24. Output: &name=tom&class.classname=class1&classmates[0].name=lily
  25. Console.log (UrlEncode (obj,' Stu '));
  26. Output: &stu.name=tom&stu.class.classname=class1&stu.classmates[0].name=lily


JS object to URL parameter (native JS and jquery two ways)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.