繁体   English   中英

在同一页面上将Javascript变量分配给php变量

[英]Assign Javascript variable to php variable on the same page

我想将javascript变量值分配给php变量。 我对此并不陌生,无法实现相同目标。 下面是我的代码:

<script type="text/javascript">
    function foo(sampleValue) 
    {
        var table = document.getElementById('mytable');
        var answer = table.rows[sampleValue].cells[1].innerText;
        alert (answer);
        window.location.href = "show.php?w1=" + answer;
    }
</script>

<?php
    if(isset($_POST['shwData']))
    {
        if(isset($_GET['w1']))
        {
            echo "this is it";
        }
    }
?>

您是否尝试过省略第一个if条件?

if(isset($_GET['w1'])) {
  echo "this is it";
}

顺便说一句:当然,您可以“将变量从javascript传递到php脚本”。 这必须通过附加请求来完成。 就像您用window.location.href = "show.php?w1=" + answer;解释了它一样 这绝对是一个选择。

根据您希望达到该值的目的以及当时的原因,您可以考虑使用AJAX。 如果请求必须对给定的(后)数据数组执行某些操作,则只需将请求发送到服务器即可。

You can do something like this:

<script type="text/javascript">
    function foo(sampleValue) 
    {
        var table = document.getElementById('mytable');
        var answer = table.rows[sampleValue].cells[0].innerHTML;

        alert (answer);
        window.location.href = "show.php?w1=" + answer;
    }


</script>
<table id="mytable">
    <tr>
        <td>my cell</td>
    </tr>
</table>

 <button onclick="foo(0)">Click me</button> 

<?php
        if(isset($_GET['w1']))
        {
            echo "this is it";
        }

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM