json转为url参数

 

//json转url参数
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);
};
var obj = {
    "name": 'tom',
    "class": {
        "className": 'class1'
    },
    "classMates": [{
        "name": 'lily'
    }]
};
console.log(parseParam(obj));//name=tom&class.className=class1&classMates[0].name=lily
console.log(parseParam(obj, 'stu'));//stu.name=tom&stu.class.className=class1&stu.classMates[0].name=lily

转载自Mr.Leo

 

 
posted @ 2018-02-28 21:50  键盘已坏  阅读(7897)  评论(0编辑  收藏  举报