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

Source: Internet
Author: User
Tags urlencode

now the JS framework encapsulates the AJAX request very simply, such as the following:
$.ajax ({type: "POST", url: "some.php", data: {name: "John", Location: ' Boston "}    }). Done (function (msg) {alert (" Data Saved: "+ msg);    });


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:
var params = ';p arams + = ' key1= ' +obj.key1;params + = ' key2= ' +obj.key2;params + = ' key3= ' +obj.key3;params + = ' key4= ' +obj.ke Y4, .....


Needless to say too much, painful ah, like hard labor, a little can not understand the programmer on the tall feeling. Maybe we can.
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
var parseparam=function (param, key) {    var paramstr= "";    if (param instanceof string| | param instanceof number| | param instanceof Boolean) {        paramstr+= "&" +key+ "=" +encodeuricomponent (param);    } else{        $.each (param,function (i) {            var k=key==null?i:key+ (param instanceof Array? ") ["+i+"] ":". " +i);            paramstr+= ' & ' +parseparam (this, k);        });    return Paramstr.substr (1);};

TestVar obj={name: ' Tom ', ' class ': {className: ' Class1 '},classmates:[{name: ' Lily '}]};p arseparam (obj);//output: " Name=tom&class.classname=class1&classmates[0].name=lily "ParseParam (obj, ' Stu ');//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:
/** * param The object that will be converted to the URL parameter String * Key URL parameter string prefix * Encode true/false URL encoding, default true * * Return URL parameter string */var UrlEncode =  function (param, key, encode) {if (param==null) return ';  var paramstr = ';  var t = typeof (PARAM); if (t = = ' string ' | | t = = ' number ' | | t = = ' Boolean ') {paramstr + = ' & ' + key + ' = ' + ((encode==null| | Encode)?  encodeURIComponent (param): param); } else {for (var i in param) {var k = key = = null? I:key + (param instanceof Array?)      ' [' + i + '] ': '. ' + i);    Paramstr + = UrlEncode (Param[i], k, encode); }} return paramstr;}; var obj={name: ' Tom ', ' class ': {className: ' Class1 '},classmates:[{name: ' Lily '}]};console.log (UrlEncode (obj));// Output: &name=tom&class.classname=class1&classmates[0].name=lilyconsole.log (UrlEncode (obj, ' Stu ')); /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.