Javascript使用jQuery将查询字符串转换为JSON并返回查询字符串

Pre*_*ngh 10 javascript jquery json query-string

希望您能找到以下用于将查询字符串转换为json对象的函数

var queryStringToJSON = function (url) {
    if (url === '')
        return '';
    var pairs = (url || location.search).slice(1).split('&');
    var result = {};
    for (var idx in pairs) {
        var pair = pairs[idx].split('=');
        if (!!pair[0])
            result[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || '');
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

用法:

获取当前Windows查询字符串

var result = queryStringToJSON() // without any parameter
Run Code Online (Sandbox Code Playgroud)

从自定义查询字符串中获取json:

var result = queryStringToJSON('?name=prem&age=30&HEIGHT=5.8')
Run Code Online (Sandbox Code Playgroud)

输出: {name:"prem", age:"30", height:"5.8"} //All keys are converted into small letters

要将其转换回url,您可以使用jQuery param方法

$.param(result)
Run Code Online (Sandbox Code Playgroud)

要操纵查询字符串,您可以在JavaScript中简单地使用标准对象操作,并再次使用$ .param方法

result.age=35;
delete result['name']; 
Run Code Online (Sandbox Code Playgroud)

Roh*_*mar 1

工作,但如果你使用了url || location.search那么你应该删除if(url === '') return ''或者它应该是这样的,

var queryStringToJSON = function (url) {
    url = url || location.search;// url or location.search
    if (url === '')
        return '';// return if url and location.search not found
    // your remainig code
}
Run Code Online (Sandbox Code Playgroud)