Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - 如何使用JQuery获取GET和POST变量?(how to get GET and POST variables with JQuery?)

How do I simply get GET and POST values with JQuery?

(如何使用JQuery简单地获取GETPOST值?)

What I want to do is something like this:

(我想做的是这样的:)

$('#container-1 > ul').tabs().tabs('select', $_GET('selectedTabIndex'));
  ask by Edward Tanguay translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For GET parameters, you can grab them from document.location.search :

(对于GET参数,您可以从document.location.search获取它们:)

var $_GET = {};

document.location.search.replace(/??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});

document.write($_GET["test"]);

For POST parameters, you can serialize the $_POST object in JSON format into a <script> tag:

(对于POST参数,您可以将JSON格式的$_POST对象序列化为<script>标记:)

<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;

document.write($_POST["test"]);
</script>

While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:

(当你在它(在服务器端做事)时,你也可以在PHP上收集GET参数:)

var $_GET = <?php echo json_encode($_GET); ?>;

Note: You'll need PHP version 5 or higher to use the built-in json_encode function.

(注意:您需要PHP 5或更高版本才能使用内置的json_encode函数。)


Update: Here's a more generic implementation:

(更新:这是一个更通用的实现:)

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

var $_GET = getQueryParams(document.location.search);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...