使用jQuery获取request url中的参数
jquery怎么得到request url中的参数呢?
其实很简单,就是循环遍历url,然后找到“&”这个符号:
demo1: js实现
下面是得到URL的数组 // Read a page's GET URL variables and return them as an associative array. function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } 1.URL如下 http://www.example.com/?me=myValue&name2=SomeOtherValue 2.我们在浏览器中可以看到数组如下 { "me" : "myValue", "name2" : "SomeOtherValue" } 3.得到相应的参数的值 var first = getUrlVars()["me"]; // To get the second parameter var second = getUrlVars()["name2"];
demo2:jQuery实现
$.extend({ getUrlVars: function(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }, getUrlVar: function(name){ return $.getUrlVars()[name]; } }); 获取相应的值的方法: // Get object of URL parameters var allVars = $.getUrlVars(); // Getting URL var by its nam var byName = $.getUrlVar('name');
demo3: 修改url中的参数
function replaceParamVal(oldUrl, paramName, replaceWith) { var re = eval('/(' + paramName + '=)([^&]*)/gi'); var nUrl = oldUrl.replace(re, paramName + '=' + replaceWith); return nUrl; }
相关推荐
zrtlin 2020-11-09
xuebingnan 2020-11-05
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
softwear 2020-08-21
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25
Aveiox 2020-06-23
dragonzht 2020-06-17