从PHP获取变量到JavaScript [duplicate]

时间:2022-11-27 21:06:44

This question already has an answer here:

这个问题已经有了答案:

I want to use a PHP variable in JavaScript. How is it possible?

我想在JavaScript中使用PHP变量。怎么可能?

6 个解决方案

#1


60  

You can print the PHP variable into your javascript while your page is created.

在创建页面时,可以将PHP变量打印到javascript中。

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.

当然,这是简单变量,而不是对象。

#2


39  

You can pass PHP Variables to your JavaScript by generating it with PHP:

可以通过PHP生成PHP变量,将PHP变量传递给JavaScript:

<?php
$someVar = 1;
?>

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>";
</script>

#3


15  

I think the easiest route is to include the jQuery javascript library in your webpages, then use JSON as format to pass data between the two.

我认为最简单的方法是在web页面中包含jQuery javascript库,然后使用JSON作为在二者之间传递数据的格式。

In your HTML pages, you can request data from the PHP scripts like this:

在HTML页面中,可以从PHP脚本中请求数据,如下所示:

$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
    alert('Result from PHP: ' + e.result);
});

In bar.php you can do this:

在酒吧。php你可以这样做:

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));

This is what's usually called AJAX, and it is useful to give web pages a more dynamic and desktop-like feel (you don't have to refresh the entire page to communicate with PHP).

这就是通常被称为AJAX的东西,它可以让web页面更动态、更像桌面的感觉(您不必刷新整个页面来与PHP通信)。

Other techniques are simpler. As others have suggested, you can simply generate the variable data from your PHP script:

其他技术更简单。正如其他人所建议的,您可以简单地从PHP脚本生成变量数据:

$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";

Most web pages nowadays use a combination of the two.

现在大多数网页都使用两者的结合。

#4


14  

It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:

这取决于您希望在Javascript中使用哪种PHP变量。例如,在Javascript中不能使用带有类方法的整个PHP对象。但是,您可以使用内置的PHP JSON (JavaScript对象表示法)函数将简单的PHP变量转换为JSON表示。如需更多资料,请参阅以下连结:

You can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

可以生成PHP变量的JSON表示,然后在页面加载时将其打印到Javascript代码中。例如:

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

#5


5  

<?php 
$j=1;
?>
<script>
var i = "<?php echo $j; ?>";
//Do something
</script>
<?php
echo $j;
?>

This is the easiest way of passing a php variable to javascript without Ajax.

这是在不使用Ajax的情况下将php变量传递给javascript的最简单方法。

You can also use something like this:

你也可以这样使用:

var i = "<?php echo json_encode($j); ?>";

This said to be safer or more secure. i think

据说这样更安全。我认为

#6


5  

Update: I completely rewrote this answer. The old code is still there, at the bottom, but I don't recommend it.

更新:我完全重写了这个答案。旧的代码仍然在底层,但是我不推荐它。


There are two main ways you can get access GET variables:

有两种方法可以获得访问变量:

  1. Via PHP's $_GET array (associative array).
  2. 通过PHP的$_GET数组(关联数组)。
  3. Via JavaScript's location object.
  4. 通过JavaScript对象的位置。

With PHP, you can just make a "template", which goes something like this:

使用PHP,您可以创建一个“模板”,大致如下:

<script type="text/javascript">
var $_GET = JSON.parse("<?php echo json_encode($_GET); ?>");
</script>

However, I think the mixture of languages here is sloppy, and should be avoided where possible. I can't really think of any good reasons to mix data between PHP and JavaScript anyway.

然而,我认为这里的混合语言是草率的,应该尽可能避免。我实在想不出有什么好的理由在PHP和JavaScript之间混合数据。

It really boils down to this:

归根结底是这样的:

  • If the data can be obtained via JavaScript, use JavaScript.
  • 如果可以通过JavaScript获取数据,请使用JavaScript。
  • If the data can't be obtained via JavaScript, use AJAX.
  • 如果不能通过JavaScript获取数据,请使用AJAX。
  • If you otherwise need to communicate with the server, use AJAX.
  • 如果您需要与服务器通信,请使用AJAX。

Since we're talking about $_GET here (or at least I assumed we were when I wrote the original answer), you should get it via JavaScript.

因为我们讨论的是$_GET(或者至少我在编写原始答案时假设我们是),所以您应该通过JavaScript获得它。

In the original answer, I had two methods for getting the query string, but it was too messy and error-prone. Those are now at the bottom of this answer.

在最初的答案中,我有两种获取查询字符串的方法,但它太混乱,容易出错。这些都在答案的底部。

Anyways, I designed a nice little "class" for getting the query string (actually an object constructor, see the relevant section from MDN's OOP article):

无论如何,我设计了一个漂亮的小“类”来获取查询字符串(实际上是一个对象构造函数,参见MDN的OOP文章中的相关部分):

function QuerystringTable(_url){
    // private
    var url   = _url,
        table = {};

    function buildTable(){
        getQuerystring().split('&').filter(validatePair).map(parsePair);
    }

    function parsePair(pair){
        var splitPair = pair.split('='),
            key       = decodeURIComponent(splitPair[0]),
            value     = decodeURIComponent(splitPair[1]);

        table[key] = value;
    }

    function validatePair(pair){
        var splitPair = pair.split('=');

        return !!splitPair[0] && !!splitPair[1];
    }

    function validateUrl(){
        if(typeof url !== "string"){
            throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;
        }

        if(url == ""){
            throw "QuerystringTable() :: Empty string given for argument <string url>";
        }
    }

    // public
    function getKeys(){
        return Object.keys(table);
    }

    function getQuerystring(){
        var string;

        validateUrl();
        string = url.split('?')[1];

        if(!string){
            string = url;
        }

        return string;
    }

    function getValue(key){
        var match = table[key] || null;

        if(!match){
            return "undefined";
        }

        return match;
    }

    buildTable();
    this.getKeys        = getKeys;
    this.getQuerystring = getQuerystring;
    this.getValue       = getValue;
}

JSFiddle demo

JSFiddle演示

function main(){
    var imaginaryUrl = "http://example.com/webapp/?search=how%20to%20use%20Google&the_answer=42",
        qs = new QuerystringTable(imaginaryUrl);

    urlbox.innerHTML = "url: " + imaginaryUrl;
    
    logButton(
        "qs.getKeys()",
        qs.getKeys()
        .map(arrowify)
        .join("\n")
    );
    
    logButton(
        'qs.getValue("search")',
        qs.getValue("search")
        .arrowify()
    );
    
    logButton(
        'qs.getValue("the_answer")',
        qs.getValue("the_answer")
        .arrowify()
    );
    
    logButton(
        "qs.getQuerystring()",
        qs.getQuerystring()
        .arrowify()
    );
}

function arrowify(str){
    return "  -> " + str;
}

String.prototype.arrowify = function(){
    return arrowify(this);
}

function log(msg){
    txt.value += msg + '\n';
    txt.scrollTop = txt.scrollHeight;
}

function logButton(name, output){
    var el = document.createElement("button");
    
    el.innerHTML = name;
    
    el.onclick = function(){
        log(name);
        log(output);
        log("- - - -");
    }
    
    buttonContainer.appendChild(el);
}

function QuerystringTable(_url){
    // private
    var url = _url,
        table = {};

    function buildTable(){
        getQuerystring().split('&').filter(validatePair).map(parsePair);
    }

    function parsePair(pair){
        var splitPair = pair.split('='),
            key       = decodeURIComponent(splitPair[0]),
            value     = decodeURIComponent(splitPair[1]);

        table[key] = value;
    }

    function validatePair(pair){
        var splitPair = pair.split('=');

        return !!splitPair[0] && !!splitPair[1];
    }

    function validateUrl(){
        if(typeof url !== "string"){
            throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;
        }

        if(url == ""){
            throw "QuerystringTable() :: Empty string given for argument <string url>";
        }
    }

    // public
    function getKeys(){
        return Object.keys(table);
    }

    function getQuerystring(){
        var string;

        validateUrl();
        string = url.split('?')[1];

        if(!string){
            string = url;
        }

        return string;
    }

    function getValue(key){
        var match = table[key] || null;

        if(!match){
            return "undefined";
        }

        return match;
    }

    buildTable();
    this.getKeys        = getKeys;
    this.getQuerystring = getQuerystring;
    this.getValue       = getValue;
}

main();
#urlbox{
    width: 100%;
    padding: 5px;
    margin: 10px auto;
    font: 12px monospace;
    background: #fff;
    color: #000;
}

#txt{
    width: 100%;
    height: 200px;
    padding: 5px;
    margin: 10px auto;
    resize: none;
    border: none;
    background: #fff;
    color: #000;
    displaY:block;
}

button{
    padding: 5px;
    margin: 10px;
    width: 200px;
    background: #eee;
    color: #000;
    border:1px solid #ccc;
    display: block;
}

button:hover{
    background: #fff;
    cursor: pointer;
}
<p id="urlbox"></p>
<textarea id="txt" disabled="true"></textarea>
<div id="buttonContainer"></div>

It's much more robust, doesn't rely on regex, combines the best parts of both the previous approaches, and will validate your input. You can give it query strings other than the one from the url, and it will fail loudly if you give bad input. Moreover, like a good object/module, it doesn't know or care about anything outside of the class definition, so it can be used with anything.

它更加健壮,不依赖regex,结合了前面两种方法的优点,并将验证您的输入。您可以将查询字符串提供给它,而不是来自url的查询字符串,如果输入错误,它将会失败。而且,像一个好的对象/模块一样,它不知道或关心类定义之外的任何东西,因此它可以与任何东西一起使用。

The constructor automatically populates its internal table and decodes each string such that ...?foo%3F=bar%20baz&ampersand=this%20thing%3A%20%26, for example, will internally become:

构造函数自动填充它的内部表并解码每个字符串,以便…?foo%3F=bar%20baz& & & & & & & & =这个%20thing%3A%20% %26,例如,在内部将变成:

{
    "foo?"      : "bar baz",
    "ampersand" : "this thing: &"
}

All the work is done for you at instantiation.

所有的工作都是在实例化时完成的。

Here's how to use it:

下面是如何使用它的方法:

var qst = new QuerystringTable(location.href);
qst.getKeys()        // returns an array of keys
qst.getValue("foo")  // returns the value of foo, or "undefined" if none.
qst.getQuerystring() // returns the querystring

That's much better. And leaving the url part up to the programmer both allows this to be used in non-browser environments (tested in both node.js and a browser), and allows for a scenario where you might want to compare two different query strings.

这是更好的。将url部分留给程序员都可以在非浏览器环境中使用(在两个节点中进行测试)。),并允许您比较两个不同的查询字符串。

var qs1 = new QuerystringTable(/* url #1 */),
    qs2 = new QuerystringTable(/* url #2 */);

if (qs1.getValue("vid") !== qs2.getValue("vid")){
    // Do something
}

As I said above, there were two messy methods that are referenced by this answer. I'm keeping them here so readers don't have to hunt through revision history to find them. Here they are:

如上所述,这个答案引用了两个混乱的方法。我把它们保存在这里,这样读者就不用在复习历史中寻找它们了。在这里,他们是:

1) Direct parse by function. This just grabs the url and parses it directly with RegEx

1)函数直接解析。这只获取url并直接使用RegEx解析它

$_GET=function(key,def){
    try{
        return RegExp('[?&;]'+key+'=([^?&#;]*)').exec(location.href)[1]
    }catch(e){
        return def||''
    }
}

Easy peasy, if the query string is ?ducksays=quack&bearsays=growl, then $_GET('ducksays') should return quack and $_GET('bearsays') should return growl

简单易行,如果查询字符串是? ducksaid = quack&bearsaid =growl,那么$_GET('ducksay ')应该返回quack, $_GET('bearsays')应该返回growl

Now you probably instantly notice that the syntax is different as a result of being a function. Instead of $_GET[key], it is $_GET(key). Well, I thought of that :)

现在您可能会立即注意到,作为函数,语法是不同的。它不是$_GET[键],而是$_GET(键)。我想过了

Here comes the second method:

第二种方法:


2) Object Build by Loop

2)对象循环构建

onload=function(){
    $_GET={}//the lack of 'var' makes this global
    str=location.search.split('&')//not '?', this will be dealt with later
    for(i in str){
        REG=RegExp('([^?&#;]*)=([^?&#;]*)').exec(str[i])
        $_GET[REG[1]]=REG[2]
    }
}

Behold! $_GET is now an object containing an index of every object in the url, so now this is possible:

看哪!$_GET现在是一个对象,包含url中每个对象的索引,因此现在可以:

$_GET['ducksays']//returns 'quack'

AND this is possible

这是可能的

for(i in $_GET){
    document.write(i+': '+$_GET[i]+'<hr>')
}

This is definitely not possible with the function.

这在函数中是不可能的。


Again, I don't recommend this old code. It's badly written.

再说一遍,我不推荐这个旧代码。这是写得很糟糕。

#1


60  

You can print the PHP variable into your javascript while your page is created.

在创建页面时,可以将PHP变量打印到javascript中。

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.

当然,这是简单变量,而不是对象。

#2


39  

You can pass PHP Variables to your JavaScript by generating it with PHP:

可以通过PHP生成PHP变量,将PHP变量传递给JavaScript:

<?php
$someVar = 1;
?>

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>";
</script>

#3


15  

I think the easiest route is to include the jQuery javascript library in your webpages, then use JSON as format to pass data between the two.

我认为最简单的方法是在web页面中包含jQuery javascript库,然后使用JSON作为在二者之间传递数据的格式。

In your HTML pages, you can request data from the PHP scripts like this:

在HTML页面中,可以从PHP脚本中请求数据,如下所示:

$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
    alert('Result from PHP: ' + e.result);
});

In bar.php you can do this:

在酒吧。php你可以这样做:

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));

This is what's usually called AJAX, and it is useful to give web pages a more dynamic and desktop-like feel (you don't have to refresh the entire page to communicate with PHP).

这就是通常被称为AJAX的东西,它可以让web页面更动态、更像桌面的感觉(您不必刷新整个页面来与PHP通信)。

Other techniques are simpler. As others have suggested, you can simply generate the variable data from your PHP script:

其他技术更简单。正如其他人所建议的,您可以简单地从PHP脚本生成变量数据:

$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";

Most web pages nowadays use a combination of the two.

现在大多数网页都使用两者的结合。

#4


14  

It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:

这取决于您希望在Javascript中使用哪种PHP变量。例如,在Javascript中不能使用带有类方法的整个PHP对象。但是,您可以使用内置的PHP JSON (JavaScript对象表示法)函数将简单的PHP变量转换为JSON表示。如需更多资料,请参阅以下连结:

You can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

可以生成PHP变量的JSON表示,然后在页面加载时将其打印到Javascript代码中。例如:

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

#5


5  

<?php 
$j=1;
?>
<script>
var i = "<?php echo $j; ?>";
//Do something
</script>
<?php
echo $j;
?>

This is the easiest way of passing a php variable to javascript without Ajax.

这是在不使用Ajax的情况下将php变量传递给javascript的最简单方法。

You can also use something like this:

你也可以这样使用:

var i = "<?php echo json_encode($j); ?>";

This said to be safer or more secure. i think

据说这样更安全。我认为

#6


5  

Update: I completely rewrote this answer. The old code is still there, at the bottom, but I don't recommend it.

更新:我完全重写了这个答案。旧的代码仍然在底层,但是我不推荐它。


There are two main ways you can get access GET variables:

有两种方法可以获得访问变量:

  1. Via PHP's $_GET array (associative array).
  2. 通过PHP的$_GET数组(关联数组)。
  3. Via JavaScript's location object.
  4. 通过JavaScript对象的位置。

With PHP, you can just make a "template", which goes something like this:

使用PHP,您可以创建一个“模板”,大致如下:

<script type="text/javascript">
var $_GET = JSON.parse("<?php echo json_encode($_GET); ?>");
</script>

However, I think the mixture of languages here is sloppy, and should be avoided where possible. I can't really think of any good reasons to mix data between PHP and JavaScript anyway.

然而,我认为这里的混合语言是草率的,应该尽可能避免。我实在想不出有什么好的理由在PHP和JavaScript之间混合数据。

It really boils down to this:

归根结底是这样的:

  • If the data can be obtained via JavaScript, use JavaScript.
  • 如果可以通过JavaScript获取数据,请使用JavaScript。
  • If the data can't be obtained via JavaScript, use AJAX.
  • 如果不能通过JavaScript获取数据,请使用AJAX。
  • If you otherwise need to communicate with the server, use AJAX.
  • 如果您需要与服务器通信,请使用AJAX。

Since we're talking about $_GET here (or at least I assumed we were when I wrote the original answer), you should get it via JavaScript.

因为我们讨论的是$_GET(或者至少我在编写原始答案时假设我们是),所以您应该通过JavaScript获得它。

In the original answer, I had two methods for getting the query string, but it was too messy and error-prone. Those are now at the bottom of this answer.

在最初的答案中,我有两种获取查询字符串的方法,但它太混乱,容易出错。这些都在答案的底部。

Anyways, I designed a nice little "class" for getting the query string (actually an object constructor, see the relevant section from MDN's OOP article):

无论如何,我设计了一个漂亮的小“类”来获取查询字符串(实际上是一个对象构造函数,参见MDN的OOP文章中的相关部分):

function QuerystringTable(_url){
    // private
    var url   = _url,
        table = {};

    function buildTable(){
        getQuerystring().split('&').filter(validatePair).map(parsePair);
    }

    function parsePair(pair){
        var splitPair = pair.split('='),
            key       = decodeURIComponent(splitPair[0]),
            value     = decodeURIComponent(splitPair[1]);

        table[key] = value;
    }

    function validatePair(pair){
        var splitPair = pair.split('=');

        return !!splitPair[0] && !!splitPair[1];
    }

    function validateUrl(){
        if(typeof url !== "string"){
            throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;
        }

        if(url == ""){
            throw "QuerystringTable() :: Empty string given for argument <string url>";
        }
    }

    // public
    function getKeys(){
        return Object.keys(table);
    }

    function getQuerystring(){
        var string;

        validateUrl();
        string = url.split('?')[1];

        if(!string){
            string = url;
        }

        return string;
    }

    function getValue(key){
        var match = table[key] || null;

        if(!match){
            return "undefined";
        }

        return match;
    }

    buildTable();
    this.getKeys        = getKeys;
    this.getQuerystring = getQuerystring;
    this.getValue       = getValue;
}

JSFiddle demo

JSFiddle演示

function main(){
    var imaginaryUrl = "http://example.com/webapp/?search=how%20to%20use%20Google&the_answer=42",
        qs = new QuerystringTable(imaginaryUrl);

    urlbox.innerHTML = "url: " + imaginaryUrl;
    
    logButton(
        "qs.getKeys()",
        qs.getKeys()
        .map(arrowify)
        .join("\n")
    );
    
    logButton(
        'qs.getValue("search")',
        qs.getValue("search")
        .arrowify()
    );
    
    logButton(
        'qs.getValue("the_answer")',
        qs.getValue("the_answer")
        .arrowify()
    );
    
    logButton(
        "qs.getQuerystring()",
        qs.getQuerystring()
        .arrowify()
    );
}

function arrowify(str){
    return "  -> " + str;
}

String.prototype.arrowify = function(){
    return arrowify(this);
}

function log(msg){
    txt.value += msg + '\n';
    txt.scrollTop = txt.scrollHeight;
}

function logButton(name, output){
    var el = document.createElement("button");
    
    el.innerHTML = name;
    
    el.onclick = function(){
        log(name);
        log(output);
        log("- - - -");
    }
    
    buttonContainer.appendChild(el);
}

function QuerystringTable(_url){
    // private
    var url = _url,
        table = {};

    function buildTable(){
        getQuerystring().split('&').filter(validatePair).map(parsePair);
    }

    function parsePair(pair){
        var splitPair = pair.split('='),
            key       = decodeURIComponent(splitPair[0]),
            value     = decodeURIComponent(splitPair[1]);

        table[key] = value;
    }

    function validatePair(pair){
        var splitPair = pair.split('=');

        return !!splitPair[0] && !!splitPair[1];
    }

    function validateUrl(){
        if(typeof url !== "string"){
            throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;
        }

        if(url == ""){
            throw "QuerystringTable() :: Empty string given for argument <string url>";
        }
    }

    // public
    function getKeys(){
        return Object.keys(table);
    }

    function getQuerystring(){
        var string;

        validateUrl();
        string = url.split('?')[1];

        if(!string){
            string = url;
        }

        return string;
    }

    function getValue(key){
        var match = table[key] || null;

        if(!match){
            return "undefined";
        }

        return match;
    }

    buildTable();
    this.getKeys        = getKeys;
    this.getQuerystring = getQuerystring;
    this.getValue       = getValue;
}

main();
#urlbox{
    width: 100%;
    padding: 5px;
    margin: 10px auto;
    font: 12px monospace;
    background: #fff;
    color: #000;
}

#txt{
    width: 100%;
    height: 200px;
    padding: 5px;
    margin: 10px auto;
    resize: none;
    border: none;
    background: #fff;
    color: #000;
    displaY:block;
}

button{
    padding: 5px;
    margin: 10px;
    width: 200px;
    background: #eee;
    color: #000;
    border:1px solid #ccc;
    display: block;
}

button:hover{
    background: #fff;
    cursor: pointer;
}
<p id="urlbox"></p>
<textarea id="txt" disabled="true"></textarea>
<div id="buttonContainer"></div>

It's much more robust, doesn't rely on regex, combines the best parts of both the previous approaches, and will validate your input. You can give it query strings other than the one from the url, and it will fail loudly if you give bad input. Moreover, like a good object/module, it doesn't know or care about anything outside of the class definition, so it can be used with anything.

它更加健壮,不依赖regex,结合了前面两种方法的优点,并将验证您的输入。您可以将查询字符串提供给它,而不是来自url的查询字符串,如果输入错误,它将会失败。而且,像一个好的对象/模块一样,它不知道或关心类定义之外的任何东西,因此它可以与任何东西一起使用。

The constructor automatically populates its internal table and decodes each string such that ...?foo%3F=bar%20baz&ampersand=this%20thing%3A%20%26, for example, will internally become:

构造函数自动填充它的内部表并解码每个字符串,以便…?foo%3F=bar%20baz& & & & & & & & =这个%20thing%3A%20% %26,例如,在内部将变成:

{
    "foo?"      : "bar baz",
    "ampersand" : "this thing: &"
}

All the work is done for you at instantiation.

所有的工作都是在实例化时完成的。

Here's how to use it:

下面是如何使用它的方法:

var qst = new QuerystringTable(location.href);
qst.getKeys()        // returns an array of keys
qst.getValue("foo")  // returns the value of foo, or "undefined" if none.
qst.getQuerystring() // returns the querystring

That's much better. And leaving the url part up to the programmer both allows this to be used in non-browser environments (tested in both node.js and a browser), and allows for a scenario where you might want to compare two different query strings.

这是更好的。将url部分留给程序员都可以在非浏览器环境中使用(在两个节点中进行测试)。),并允许您比较两个不同的查询字符串。

var qs1 = new QuerystringTable(/* url #1 */),
    qs2 = new QuerystringTable(/* url #2 */);

if (qs1.getValue("vid") !== qs2.getValue("vid")){
    // Do something
}

As I said above, there were two messy methods that are referenced by this answer. I'm keeping them here so readers don't have to hunt through revision history to find them. Here they are:

如上所述,这个答案引用了两个混乱的方法。我把它们保存在这里,这样读者就不用在复习历史中寻找它们了。在这里,他们是:

1) Direct parse by function. This just grabs the url and parses it directly with RegEx

1)函数直接解析。这只获取url并直接使用RegEx解析它

$_GET=function(key,def){
    try{
        return RegExp('[?&;]'+key+'=([^?&#;]*)').exec(location.href)[1]
    }catch(e){
        return def||''
    }
}

Easy peasy, if the query string is ?ducksays=quack&bearsays=growl, then $_GET('ducksays') should return quack and $_GET('bearsays') should return growl

简单易行,如果查询字符串是? ducksaid = quack&bearsaid =growl,那么$_GET('ducksay ')应该返回quack, $_GET('bearsays')应该返回growl

Now you probably instantly notice that the syntax is different as a result of being a function. Instead of $_GET[key], it is $_GET(key). Well, I thought of that :)

现在您可能会立即注意到,作为函数,语法是不同的。它不是$_GET[键],而是$_GET(键)。我想过了

Here comes the second method:

第二种方法:


2) Object Build by Loop

2)对象循环构建

onload=function(){
    $_GET={}//the lack of 'var' makes this global
    str=location.search.split('&')//not '?', this will be dealt with later
    for(i in str){
        REG=RegExp('([^?&#;]*)=([^?&#;]*)').exec(str[i])
        $_GET[REG[1]]=REG[2]
    }
}

Behold! $_GET is now an object containing an index of every object in the url, so now this is possible:

看哪!$_GET现在是一个对象,包含url中每个对象的索引,因此现在可以:

$_GET['ducksays']//returns 'quack'

AND this is possible

这是可能的

for(i in $_GET){
    document.write(i+': '+$_GET[i]+'<hr>')
}

This is definitely not possible with the function.

这在函数中是不可能的。


Again, I don't recommend this old code. It's badly written.

再说一遍,我不推荐这个旧代码。这是写得很糟糕。