window.location.search查询为JSON [英] window.location.search query as JSON

查看:484
本文介绍了window.location.search查询为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好的方法将URL的location.search转换为对象?也许只是更有效或更精简?我使用的是jQuery,但纯JS也可以使用.

Is there a better way to convert a URL's location.search as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.

var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });

推荐答案

这是一个纯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". ;)

这篇关于window.location.search查询为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆