且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

window.location.search查询为JSON

更新时间:2023-11-30 23:12:34

这是一个纯JS函数.解析当前URL的搜索部分并返回一个对象. (记住,这有点冗长,可读性.)

Here's a pure JS function. Parses the search part of the current URL and returns an object. (It's a bit verbose for readability, mind.)

function searchToObject() {
  var pairs = window.location.search.substring(1).split("&"),
    obj = {},
    pair,
    i;

  for ( i in pairs ) {
    if ( pairs[i] === "" ) continue;

    pair = pairs[i].split("=");
    obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
  }

  return obj;
}

在相关说明中,您不是试图将单个参数存储在"JSON"中,而是存储在对象"中. ;)

On a related note, you're not trying to store the single parameters in "a JSON" but in "an object". ;)