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

Pass variables from Javascript to PHP - Popup/Modal Window

本文关键字:窗口 PHP 模态 变量 Javascript      更新时间:2023-09-26
<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 时,我正在尝试开辟一种方法。它不起作用,有人可以帮助我吗?感谢

如果您对页面重新加载感到满意,您可以简单地执行

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>

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