Query-string encoding of a Javascript Object

前端 未结 30 2956
渐次进展
渐次进展 2020-11-22 00:23

Do you know a fast and simple way to encode a Javascript Object into a string that I can pass via a GET Request?

No jQuery, no

30条回答
  •  死守一世寂寞
    2020-11-22 00:57

    A small amendment to the accepted solution by user187291:

    serialize = function(obj) {
       var str = [];
       for(var p in obj){
           if (obj.hasOwnProperty(p)) {
               str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
           }
       }
       return str.join("&");
    }
    

    Checking for hasOwnProperty on the object makes JSLint/JSHint happy, and it prevents accidentally serializing methods of the object or other stuff if the object is anything but a simple dictionary. See the paragraph on for statements in this page: http://javascript.crockford.com/code.html

提交回复
热议问题