【问题标题】:Changing PHP variables after DOM load, will changes reflect?在 DOM 加载后更改 PHP 变量,更改会反映吗?
【发布时间】:2014-07-22 01:03:00
【问题描述】:

一个朋友问了我一个问题,老实说,我这辈子都想不出一个肯定的答案。所以我把它摆给你;

如果我有 2 个文档(page.html 和 form.php),并且我在 page.html 中包含了 form.php:

<html>
   <head>
      <title>Home</title>
      <?php include 'form.php'; ?>
   </head>
   <body>
      <form>
        <FORM CONTENT HERE>

      </form>

      <div class="results">
      <p><?php echo $result_variable ?></p>
      </div>
   </body>
 <script>
    !-- Ajax function here, POSTs to form.php
 </script>

</html>

它有一个 AJAX 表单,POSTing to form.php,以及一个用于打印 PHP 变量 $result_variable 的结果字段。

现在,如果我的 PHP 页面采用发布的数据,在初始文档加载/包含完成后 - 然后更改 $result_variable 的值作为结果 - 将在 page.html 中更新 $result_variable 的值而不页面重新加载?

例如 - 如果 form.php 看起来像这样;

<?php
$result_variable = 1;

if (!empty($_POST)){
$result_variable = 2;
}

?>

在初始页面加载后(不提交表单),$result_variable 应该是 1。虽然在 ajax 表单提交完成后,$result_variable 已更改为 2。这会在不重新加载 page.html 的情况下反映吗?

谢谢。

【问题讨论】:

  • 如果您的 AJAX 请求的 Javascript 响应处理程序将响应文本设置为您的 $result_variable&lt;p&gt; 标记,则会这样做。如果这就是您的要求,它不会神奇地发生。
  • 谢谢,这正是我想要的。您是否有任何关于如何以类似方式处理 AJAX 请求以完成上述任务的读物​​?
  • 不幸的是,绝大多数示例都是jQuery。但是在页面中,您将使用(唯一的)id,例如 &lt;p id='destination'...,然后在响应处理程序中设置 document.getElementById('destination').textContent = response;response 是脚本返回的内容。
  • 这是现场直播jQuery form submit example。 jQuery 确实让 Ajax 变得简单得多,但我仍然建议您尝试使用原生方法,以便您知道它在做什么。
  • 完美。干杯,这非常有帮助!

标签: javascript php html ajax


【解决方案1】:

不。因为$result_variable 不是包含form.php 的当前页面的一部分。

只有使用 javascript 填充它才会起作用。

假设:

ajax 以 form.php 为目标,所以 form.php 应该是这样的:

<?php

  $result_variable = 1;

  if(!empty($_POST)){
    $result_variable = 2;
  }

  // print the result as an ajax response (the format here is not JSON)
  echo $result_variable;

  // if the response format is JSON
  echo json_encode(array("result_key_name" => $result_variable));
?> 

这是一个使用 jQuery 的示例 $.post http://api.jquery.com/jquery.post/

// on a normal php/html page
$.post("form.php", form_data, function(data){
   // data is the result echoed using json_encode() from form.php
   alert(data.result_key_name); // as per the server-side example above
}, "json");

【讨论】:

  • 非常感谢!你有什么我可以读到的关于如何通过 Javascript 响应处理程序(来自 AJAX 请求)或通过其他方式来反映更改的内容吗?
  • 你用 jQuery 做 ajax 吗?
  • 暂时没有,不过我很乐意调查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多