-1

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

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

当页面第一次加载时,它运行 getData 函数——一切都按预期工作。但是稍后在页面下方,当我尝试加载 pullData.php 时,srcAverage 不会更新为新值。JS 警报显示 srcAverage 值。

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

我觉得我做错了一件非常小的事情 - 想法?

连接文件

<?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() 加载时,该变量不会传递给 index.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;
}

}
?>
4

3 回答 3

1

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

如果您想获得新值,您可能应该切换到使用$.ajax()而不是.load(),并pullData.php回显结果,json以便您可以在 javascript 中处理响应。

于 2013-10-30T17:26:28.967 回答
0

将其作为新参数传递

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

然后在服务器上:

$_POST['myVar']; 

将包含该值。

编辑

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

$('#element').load('file.php', function(data){
    //response from the server
});
于 2013-10-30T17:22:31.303 回答
0

您的问题是您正在通过 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);
?>
于 2013-10-30T17:33:24.623 回答