PHP jQuery:将PHP变量从(而不是)传递到$.load()
我看到过一些问题,询问如何将变量发送到以$.load加载的文档,而不是从$.load检索变量 我已经在下面粘贴了相关的代码片段;基本上,我要做的是每隔一段时间运行一次PHP函数,最初是在页面首次加载时运行 当页面第一次加载时,它会运行getData函数,并且一切都按预期工作。但是稍后在页面下,当我尝试加载pullData.php时,srceaverage不会用新值更新。JS警报显示SRC平均值 示例:第一次运行页面时,srceaverage为X。每5秒,我们要加载pullData.php并使用新值(更改X)更新index.php上的srceaverage 我觉得我做错了一件很小的事情——想法 conn.phpPHP jQuery:将PHP变量从(而不是)传递到$.load(),php,jquery,global-variables,Php,Jquery,Global Variables,我看到过一些问题,询问如何将变量发送到以$.load加载的文档,而不是从$.load检索变量 我已经在下面粘贴了相关的代码片段;基本上,我要做的是每隔一段时间运行一次PHP函数,最初是在页面首次加载时运行 当页面第一次加载时,它会运行getData函数,并且一切都按预期工作。但是稍后在页面下,当我尝试加载pullData.php时,srceaverage不会用新值更新。JS警报显示SRC平均值 示例:第一次运行页面时,srceaverage为X。每5秒,我们要加载pullData.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>
<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>
$(文档).ready(函数(){
setInterval(函数(){
//每个间隔,获取第一个和第二个值
$(“#targetDiv”).load(“pullData.php”);
警报(“新值为”);
},5000);//结束设置间隔
});
pullData.php
<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
getData($src, $mysqli);
?>
<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
echo getData($src, $mysqli);
?>
getData函数(参见下面的代码)从单独的表中获取4个值,将它们平均化(为了便于故障排除,我在不同的语句和变量中将它们分开),然后将变量srcAverage设置为平均值。我已经测试了MySQLi语句是否工作正常,并且srceaverage被函数指定了正确的值。回声或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;
}
}
?>
将其作为新参数传递
$("#element").load("file.php", { 'myVar' : 'someValue'} );
然后在服务器上:
$_POST['myVar'];
将包含该值
编辑
也许我理解错了,如果要从load函数访问数据,需要使用回调函数
$('#element').load('file.php', function(data){
//response from the server
});
您误解了php页面的生命周期<代码>仅在最初加载/呈现页面时计算一次
如果您想获得新值,您可能应该切换到使用
$.ajax()
而不是.load()
,并让pullData.php
将结果作为json
进行回显,这样您就可以在javascript中处理响应。您的问题是通过php回显$srcAverage。浏览器不从服务器获取php,也不知道如何执行它,它只看到php脚本的结果。因此,如果查看源,您将看到所有警报都是:
alert('New value is ');
php已经运行,$srcmaverage在回显时由于作用域未定义,因此它放置了一个null,该值将转换为空字符串
$.load加载的是pullData.php的结果,它已经被php解析并通过服务器返回。pullData.php没有输出。您需要回显getData的结果,以便javascript可以看到它
在javascript中,您需要做的是:
alert('New value is ' + $('#targetDiv').html());
根据您的示例标记,您似乎也缺少了#targetDiv。您可能希望将原始getData包装在#targetDiv中
因此,您的固定版本如下所示:
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>
<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>
$(文档).ready(函数(){
setInterval(函数(){
//每个间隔,获取第一个和第二个值
$(“#targetDiv”).load(“pullData.php”);
警报('新值为'+$('#targetDiv').html();
},5000);//结束设置间隔
});
pullData.php
<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
getData($src, $mysqli);
?>
<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
echo getData($src, $mysqli);
?>
这与OP想要做的正好相反,这是有道理的。我只使用json。谢谢:)@Evan从外观上看,问题是将变量从PHP传递到Javascript,而不是从Javascript传递到PHP。@Evan:这不是问题的重复。正如MWJump上面所说的,我想从文件中传递,而不是传递到。谢谢你,你的解决方案非常有用,而且信息丰富。它也起到了作用:)将此解决方案标记为最佳解决方案,因为它最符合问题的上下文。在function.php中,我在返回之前回显了srcmaverage,然后根据建议更改了JS中的警报-警报显示了预期的值。非常感谢。