PHP jQuery:传递PHP变量FROM(而不是)$ .load()

时间:2013-10-30 17:15:17

标签: php jquery global-variables

我看到过有关将变量发送到$ .load中加载的文档但没有从$ .load中检索变量的问题。

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

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

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

我觉得这是非常小的我做错了 - 想法?

conn.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
?>

的index.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>

pullData.php

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

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

function.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;
}

}
?>

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

将其作为新参数传递

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

然后在服务器上:

$_POST['myVar']; 

将包含值。

修改

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

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

答案 2 :(得分: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中。

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

的index.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>

pullData.php

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