dpymrcl269187540 2012-05-16 20:54
浏览 22
已采纳

如何使用地址栏将值从javascript传递给php

I have .js and .php files and html pages. I am including js files in html files and php files in js files.

I want to pass 'cat' value from js file to php file using address bar when I go to this page;

/demo/convert.html?cat=volume

But I have no idea how to do this.

By the way, this is a blacberry project and I am not sure if I can use address bar to pass value. Any idea is welcome.

  • 写回答

2条回答 默认 最新

  • duanfeiqu1989 2012-05-16 21:03
    关注

    Test this sample code with an URL like : http://sputnick-area.net/test/index.php?foobar=works_as_a_charm

    <?php
    
    $var = $_GET['foobar'];
    
    echo <<<EOF
    <html>
    <head>
    <title></title>
    </head>
    <body>
    demo of using PHP GET variable in Javascript :
    <script type="text/javascript">
    alert("$var");
    </script>
    </body>
    </html>
    EOF
    
    ?>
    

    Edit :

    if you'd like to handle GET variables from within JavaScript, consider the following HTML + JavaScript sample : http://sputnick-area.net/test/index.html?foobar=works_as_a_charm

    <html>
    <head>
    <title></title>
    </head>
    <body>
    <script type="text/javascript">
    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];
    }
    
    alert(vars['foobar']);
    </script>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?