如何使用JQuery获取GET和POST变量?

99

如何使用jQuery简单地获取GETPOST的值?

我想做的事情类似于这样:

$('#container-1 > ul').tabs().tabs('select', $_GET('selectedTabIndex'));
14个回答

1
使用以下函数:

var splitUrl = function() {
    var vars = [], hash;
    var url = document.URL.split('?')[0];
    var p = document.URL.split('?')[1];
    if(p != undefined){
        p = p.split('&');
        for(var i = 0; i < p.length; i++){
            hash = p[i].split('=');
            vars.push(hash[1]);
            vars[hash[0]] = hash[1];
        }
    }
    vars['url'] = url;
    return vars;
};

您可以通过 vars['index'] 访问变量,其中 'index' 是get变量的名称。


这段代码对于像 http://foo.com/?a=b#bar 这样的UTL失败了。它认为 b#bara 的值。 - M.M

1

简单而实用的从URL获取变量/值的方法:

function getUrlVars() {
    var vars = [], hash, hashes = null;
    if (window.location.href.indexOf("?") && window.location.href.indexOf("&")) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    } else if (window.location.href.indexOf("?")) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
    }
    if (hashes != null) {
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}

我在互联网上找到了它,只是修复了一些错误。

0

我的方法:

var urlParams;
(window.onpopstate = function () {
var match,
      pl     = /\+/g,  Regex for replacing addition symbol with a space
       search = /([^&=]+)=?([^&]*)/g,
      decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
       query  = window.location.search.substring(1);
   urlParams = {};
   while (match = search.exec(query))
    urlParams[decode(match[1])] = decode(match[2]);
})();

-1

仅供记录,我想知道这个问题的答案,所以我使用了一个PHP方法:

<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
    foreach($_GET as $key => $val)
        echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>

这样,我所有在此之后运行的JavaScript/jQuery都可以访问jGets中的所有内容。我觉得这是一个不错而优雅的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接