PHP jQuery:传递一个 PHP 变量 FROM (not to) $.load()


PHP jQuery: Passing a PHP variable FROM (not to) $.load()

我看到过一些问题,询问将变量发送到在 $.load 中加载的文档,但不从 $.load 中检索变量。

我已经粘贴了下面的相关代码片段;基本上,我试图做的是每隔一段时间运行一个PHP函数,最初在页面首次加载时。

当页面首次加载时,它会运行 getData 函数 - 一切都按预期工作。但是在页面的后面,当我尝试加载 pullData.php 时,srcAverage 不会使用新值更新。JS 警报显示 src平均值。

示例:第一次运行页面时,srcAverage 为 X。每 5 秒,我们希望加载 pullData.php并使用新值(更改 X)更新索引上的 srcAverage.php。

我觉得这是我做错了的真的很小的事情——想法?

康恩.php

<?php
define("HOST", "stuff");
define("USER", "stuff");
define("PASSWORD", "stuff");
define("DATABASE", "stuff");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Connection info above all works as intended
?>

索引.php

<?php
include 'inc/conn.php';
include 'inc/function.php';
$src = "none";
getData($src, $mysqli);
// This initial run of getData works as intended
// Skip to further down
// The JS alert below does NOT reflect the new srcAverage
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
    // each interval, get first and second values
    $("#targetDiv").load("pullData.php");
    alert('New value is <?php echo $srcAverage; ?>');
    }, 5000); // end setInterval
});
</script>

拉数据.php

<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
getData($src, $mysqli);
?>

getData 函数(见下面的代码)从单独的表中获取 4 个值,将它们平均在一起(出于故障排除目的,我将它们全部分隔在不同的语句和变量中),然后将变量 srcAverage 设置为平均值。我已经测试了MySQLi语句是否正常工作,并且该函数为srcAverage分配了正确的值。回显或 JS 警报按预期显示值(在此页面上)。但是当通过 load() 加载时.php变量不会传递给索引。

功能.php

<?php
function getData($src, $mysqli) {
    // Check SRC for specific source
    // If no specific source, get average of all sources
    // If YES specific source, get that value
    global $srcAverage;
    if ($src == 'alt') {
        if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($altVal); // get variables from result.
      $stmt->fetch();
      if($stmt->num_rows == 1) { // The entry exists, good to go
         // echo $altVal;
      }
      } else {
         // Either no results pulled or more than one.
         echo "Error pulling alternate data!"; 
         return false;
      }
    }
    else {
    // Value 1  
      if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($firstVal); // get variables from result.
      $stmt->fetch();
      if($stmt->num_rows == 1) {
         // echo $firstVal; // This works as intended
      }
      } else {
         // Either no results pulled or more than one.
         echo "Error pulling first value data!"; 
         return false;
      }
     // Value 2
      if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($secondVal); // get variables from result.
      $stmt->fetch();
      if($stmt->num_rows == 1) { // The entry exists, good to go
         // echo $secondVal;
      }
      } else {
         // Either no results pulled or more than one.
         echo "Error pulling second value data!"; 
         return false;
      }
     // Value 3
      if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($thirdVal); // get variables from result.
      $stmt->fetch();
      if($stmt->num_rows == 1) { // The entry exists, good to go
         // echo $thirdVal;
      }
      } else {
         // Either no results pulled or more than one.
         echo "Error pulling third value data!"; 
         return false;
      }
     // Value 4
      if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) { 
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($fourthVal); // get variables from result.
      $stmt->fetch();
      if($stmt->num_rows == 1) { // The entry exists, good to go
         // echo $fourthVal;
      }
      } else {
         // Either no results pulled or more than one.
         echo "Error pulling fourth value data!"; 
         return false;
      }
// So everything up to this point is working fine. Statements grab data as intended, and assign variables.
// We have data - move forward 
      $srcCount = 4;
      $srcTotal = $firstVal + $secondVal + $thirdVal + $fourthVal;
      $srcAverage = $srcTotal / $srcCount;
      $srcAverage = number_format((float)$srcAverage, 2, '.', '');
// echo "Total: $srcTotal    ....    Average: $srcAverage";
// If we were to echo above, it would display correctly. Problem is passing the variable to index
      return $srcAverage;
}
}
?>

你误解了 php 页面的生命周期。 <?php echo $srcAverage; ?>仅在最初加载/呈现页面时计算一次。

如果你想得到新值,你可能应该切换到使用$.ajax()而不是.load(),并且pullData.php结果回显为json这样你就可以在javascript中使用响应。

你的问题是你通过php回显$srcAverage。浏览器没有从服务器获取php或知道如何执行它,它只看到php脚本的结果。因此,如果您查看源代码,您将看到所有警报都是:

alert('New value is ');

php 已经运行了,$srcAverage当它被回显时由于作用域而未定义,因此它放置了一个转换为空字符串的 null

$.load 加载的是 pullData.php 的结果,已经被 php 解析并通过服务器返回。 pullData.php 没有输出。你需要回显getData的结果,以便javascript可以看到它。

在javascript中你需要做的是:

alert('New value is ' + $('#targetDiv').html());

根据您的示例标记,您似乎也缺少 #targetDiv。您可能希望将原始 getData 包装在 #targetDiv 中。

因此,您的固定版本如下所示:

索引.php

<div id='targetDiv'>
<?php
include 'inc/conn.php';
include 'inc/function.php';
$src = "none";
echo getData($src, $mysqli);
// This initial run of getData works as intended
// Skip to further down
// The JS alert below does NOT reflect the new srcAverage
?>
</div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
    // each interval, get first and second values
    $("#targetDiv").load("pullData.php");
    alert('New value is ' + $('#targetDiv').html();
    }, 5000); // end setInterval
});
</script>

拉数据.php

<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
echo getData($src, $mysqli);
?>

将其作为新参数传递

$("#element").load("file.php", { 'myVar' : 'someValue'} );

然后在服务器上:

$_POST['myVar']; 

将包含该值。

编辑

也许我误解了,如果你想从加载函数访问数据,你需要使用回调。

$('#element').load('file.php', function(data){
    //response from the server
});