2016-06-08 83 views
-2

我有一种可能的方式在jQuery url中使用GET变量。就像在PHP中,我们有这样的事情:JQuery URL GET变量

header('location : path/to/page.php?id='.$id); 

,并在page.php文件,我们这样做:

$id = $_GET['id']; 

所以在jQuery的,我们可以这样做:

window.location.replace(path/to/page.html/* and pass the url query here*/); 
+0

为什么要投票? –

+0

你想重写路径'path/to/page.php?id =?'到'path/to/page.html'为什么不使用htaccess? – madalinivascu

回答

2

我认为你要找的是访问javascript中的查询字符串($ _GET in php)变量。你可以使用这个功能。

function getParameterByName(name, url) { 
    if (!url) url = window.location.href; 
    name = name.replace(/[\[\]]/g, "\\$&"); 
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), 
     results = regex.exec(url); 
    if (!results) return null; 
    if (!results[2]) return ''; 
    return decodeURIComponent(results[2].replace(/\+/g, " ")); 
} 

,然后调用getParameterByName('id')得到当前URL的?id=val一部分。

0

你也可以使用位置将数据传递到另一个页面。替换:

idVal = 1; 
window.location.replace("path/to/page.php?id="+idVal); 
0

使用js函数来做到这一点...

var 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(decodeURIComponent(hash[0])); 
      vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]); 
     } 
     if(vars[0] == window.location.href){ 
      vars =[]; 
     } 
     return vars; 
    } 

然后在任何你想使用

var params = getUrlVars(); 
console.log(params["id"]); 
console.log(params["whatever"]); 

你可以使用任何你想要的。