扩展 location 对象

  在AJAX的应用中,往往需要通过URL地址传递一些参数。一般情况下我们常见的是形如 index.html?name=3&size=14 这样的通过location.search对象传递。而为了解决AJAX交互过程中无法使用浏览器的前进后退按钮的问题,也常用形如index.html#name=3&size=14这样的通过location.hash对象传递。我们需要对此进行处理,获取传递的参数名和参数值。

  下面这段代码扩展了location对象,增加了2个属性和2个方法。

Properties
params 对象,存放 location.search 中的参数名和参数值。形如 params[ name ] = value
hashes 对象,存放 location.hash 中的参数名和参数值。形如 params[ name ] = value
Mehtods
getParams 解析 location.search 中的参数
getHashes 解析 location.hash 中的参数

 

	location.params	= {};
	location.hashes	= {};
	
	location.params.toString = function()
	{
		var _ostParams = "";
		for ( i in location.params )
		{
			_ostParams += i + " : " + location.params[i] + "\n";
		}
		return _ostParams;
	}
	
	
	
	location.hashes.toString = function()
	{
		var _ostHashes = "";
		for ( i in location.hashes )
		{
			_ostHashes += i + " : " + location.hashes[i] + "\n";
		}
		return _ostHashes;
	}

	location.getParams = function()
	{
	
		var _queryString = location.search.substr( 1 , location.search.length );
		if ( _queryString != null && _queryString != "" )
		{
			var _queries = _queryString.split("&");
			for ( var i = 0 ; i < _queries.length ; i++ )
			{
				var _query = _queries[i].split("=");
				location.params[ _query[0] ] = unescape( _query.slice(1).join("=") );
			}
		}
	}
	
	location.getHashes = function()
	{

		var _hashestring = location.hash.substr( 1 , location.hash.length );
		if ( _hashestring != null && _hashestring != "" )
		{
			var _hashes = _hashestring.split("&");
			for ( var i = 0 ; i < _hashes.length ; i++ )
			{
				var _hash = _hashes[i].split("=");
				location.hashes[ _hash[0] ] = unescape( _hash.slice(1).join("=") );
			}
		}
	}

评论

看这个地址

http://blog.imkink.com/files/script_sample/demo.location.html?url=3&id=14#target=client&method=post

你可以修改后面的这些参数名或值看看结果有何不同。

弱问一个能否给个demo

我没有系统的学过javascript,没有类啊对象的概念,不知道怎么用这段代码。
直接document.write(location.params);不行啊。

发表新评论

Please solve the math problem above and type in the result. e.g. for 1+1, type 2.
此内容将保密,不会被其他人看见。
  • 允许的 HTML 标签: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • 行和段被自动切分。

更多格式化选项信息