【问题标题】:How to get a PHP variable in JavaScript in this case?在这种情况下如何在 JavaScript 中获取 PHP 变量?
【发布时间】:2018-12-02 12:31:23
【问题描述】:

在以下情况下,我希望我的脚本运行 post.php。这很好用。但是在运行 post.php 文件时,应该在其中创建一个内容为“1”的变量。我想在我的 javascript 中取回变量。所以有两个文件:

index.php 的一部分

<script type="text/javascript">
        function post()
        {
            var message = $('#message').val();
            $.post('post.php', {postmessage:message},
            function(data)
            {
                $('#result').html(data);
            });
        }
</script>

然后我有 post.php,其中应该创建内容为“1”的变量.. 然后我想在脚本中的 index.php 中取回它。我该怎么做?

我为什么要这样做?当在 post.php 中创建一个内容为“1”的变量时,>>我认为它必须是一个 $_POST 变量?

【问题讨论】:

  • 可以是post,也可以是get,无所谓。您可以通过邮政发送更多数据(甚至通过fedex发送更多数据)。还要注意$.post()$.ajax()的简写形式,因此请先学习较长的形式。

标签: javascript php jquery ajax variables


【解决方案1】:

其中一种方法是从您的 post.php 文件中返回 JSON 编码的变量。服务器响应后,来自文件的响应位于 $.post 方法的回调函数参数中的 data 变量中。

请注意,您还需要在前端将这些数据从 JSON 解析为纯 JS,以便您可以使用它。代码可能如下所示:

前端 - index.php:

<script type="text/javascript">
    function post()
    {
        var message = $('#message').val();
        $.post('post.php', {postmessage:message},
        function(data)
        {
            var parsedData = JSON.parse(data);
            $('#result').html(parsedData);
        });
    }
</script>

后端 - post.php:

<?php
// get sent variable
$message = $_POST['postmessage'];

// do what you need to do with that

// consider your processing resulting in success
$success = true;

echo json_encode($success);
?>

【讨论】:

  • @kadnick 这个答案的关键部分是使用echo - 这就是您将响应从 PHP 端发送到 javascript/ajax 端的方式。
  • 为了安全加载您的服务器,请考虑调用“exit;”在 echo 之后或使用 die 代替 echo 例如死(json_encode($success));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多