由于遇到相关序列化的问题,但是vue项目中由于减少队jquery引用的限制,导致不能用$.param来序列化参数,所以写了如下方法用来解决相关问题,但由于考虑不全,可能存在判断不全或者代码冗余等情况,希望多提意见,多多改善

var personObj = {
    name:'cheny0815',
    age:24,
    c:[{
        id:1,
        name:2
    },{
        id:2,
        name:3
    }],
    other:{
        a:1,
        b:{
            c:2,
            d:{
                a:1,
                b:{
                    e:1,
                    f:2
                }
            }
        }
    },
}
var nextStr = '';

function changeDataType(obj){
    let str = ''
    if(typeof obj == 'object'){
        for(let i in obj){
            if(typeof obj[i] != 'function' && typeof obj[i] != 'object'){
                str += i + '=' + obj[i] + '&' ;
            }else if (typeof obj[i] == 'object'){
                nextStr = '';
                str += changeSonType(i, obj[i])
            }
        }
    }
    return str.replace(/&$/g, '');
}

function changeSonType(objName, objValue){
    if(typeof objValue == 'object'){
        for(let i in objValue){
            if(typeof objValue[i] != 'object'){
                let value = objName + '[' + i + ']=' + objValue[i];
                nextStr += encodeURI(value) + '&';
            }else{
                changeSonType(objName + '[' + i + ']', objValue[i]);
            }
        }
    }
    return nextStr;
}

var resultParam = $.param(personObj);
var resultMyself = changeDataType(personObj);
document.write('resultMyself===>' + resultMyself + '<br><hr>')
document.write('resultParam ===>' + resultParam + '<br><hr>')
document.write('resultMyself === resultParam ===>' + (resultMyself === resultParam))

结果如下:

结果图

序列化后传参效果图

Logo

前往低代码交流专区

更多推荐