JS变量(名称)到PHP变量($ _POST [" name"])

时间:2018-03-01 02:03:08

标签: javascript php jquery html

我在哪里犯错误?

HTML:

<p><?php echo($_POST['name']); ?></p>

PHP:

if(isset($_POST["submit"]))
{
    ?>
    <script type='text/javascript'>
    var name = "John";

    function from_js_to_php()
    {
        $.ajax({
        type: 'POST',
        url: 'index.php',
        data: {name: name}
        })
    }

    $(document).ready(from_js_to_php);
    </script>
    <?php
}

我想将JS变量name发送到PHP变量$_POST["name"]
index.phpindex.php,所以同一页面。

我阅读并尝试了很多选项,但我要么不理解,要么这个选项对我不起作用。

我是初学者,英语不好,所以我很抱歉经常出现误会

1 个答案:

答案 0 :(得分:0)

由于你想要的是将POST变量发送到当前页面,我能想到的唯一方法是使用HTML表单。

<form action="index.php" method="post" id="hidden-form" style="display:none">
    <input type="hidden" value="John" name="name">
</form>

提交此表单后,页面将被重定向到index.php,其中包含数据name的POST请求,这就是您想要的。

您可以使用Javascript来控制表单提交

document.getElementById("hidden-form").submit(); 
相关问题