将变量从Javascript传递到PHP - 弹出/模态窗口

时间:2016-02-18 09:43:57

标签: javascript php html variables modal-dialog

<html>
<head>
        <script type="text/javascript">
            function showdivv(el, idclicked) {
                var iddd = idclicked;
                var display = document.getElementById(el).style.display;
                if(display == "none")
                    document.getElementById(el).style.display = 'block';
                else
                    document.getElementById(el).style.display = 'none';
            }
        </script>
        <?php  $showw = "<script>document.write(iddd)</script>"; ?>
</head>
<body>
    <div id="myDiv" style="display: none;">ID Selected: <?php echo $showw; ?></div>
    <?php $variable = 4; ?>
    <button type="button" onclick="showdivv('myDiv', '<?php echo $variable; ?>')">Show / Hide</button>
</body>

当我按下按钮时,我试图通过变量(在本例中为ID)传递给JavaScript,然后在PHP中显示隐藏的div。它不起作用,有人可以帮助我吗? THX

1 个答案:

答案 0 :(得分:0)

如果你对网页重新加载没问题,你可以直接进行

window.location.href('php_script_that_needs_your_input.php?id=input_id_from_js');

如果没有,我绝对建议使用JQuery,因为它使Ajax查询变得轻而易举。

<head>标记内:

<script src='http://code.jquery.com/jquery-2.2.0.min.js'></script>

显然,将脚本上传到您自己的服务器用于生产目的。

<body>中,您希望PHP脚本的结果出现(如果您不想从PHP输出,请跳过此步骤):

<div id="phpResult"><!--content to be set by ajax--></div>

并将此JS直接放在此<div>

之下
function ajax_on_button_press(resultDiv, id) {
   var phpUrl = "php_script.php?id="+id+"&other_variable=cheese&more_info=rats";
   $(resultDiv).load(phpUrl);
}

我在这里使用了示例值,但您可以轻松地使用JavaScript中的变量:

var other_variable=$('#otherVariableInput').val(); //gets input from a textbox with the html id otherVariableInput
var phpUrl = "php_script.php?id="+id+"&other_variable="+other_variable+"&more_info=rats";

要启动此过程,您需要一个运行此脚本的按钮。将按钮标记更改为

<button type="button" onclick="ajax_on_button_press('#phpResult', '<?php echo $variable; ?>')">Show / Hide</button>

如果我理解正确,那应该可以解决你的问题。