我在获取使用jQuery的PHP变量时遇到问题。
我在主体中定义了一个PHP变量$x,并将其发送到一个PHP文件中。PHP文件echo的变量值。
在jQuery脚本中,我创建了一个Javascript变量:
var test_php_variable = <?php echo $x; ?> ; //$x is undefined, why?
当执行这行代码时,看起来$x没有定义。我本来会这么想的,因为它被封装在$(document).ready(function(){};标记,它将等待HTML主体中的PHP代码首先执行。
这行代码有效,但不允许我使用变量:
var test_php_variable = <?php echo 10; ?> ; // no problems with a constant
一件有趣的事情是,当我在HTML主体的末尾包含所有jQuery代码时,代码就可以工作了。
如果我在HTML头中使用这段代码,为什么$x是未定义的?
HTML/j查询代码:
<html>
<head>
<!--load jQuery from Google -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type ="text/javascript">
//wait until the document is ready - maybe it is loading the javascript
//before the document is ready?
$(document).ready(function() {
//the line of code below does not work, $x is not defined
var test_php_variable = <?php echo $x; ?> ;
$('#Update_variable').click(function(){
//give a "Loading..." message
$('div#test1 span').html('Loading...')
//ask the server to echo "test_variable"
//place "test_variable" in the span of #test1
$.get('server_response.php',
'test_variable=' + test_php_variable,
function(data){
$('div#test1 span').html(data);
}, 'html'); //end $.get
}); //end click
}); //end document ready
</script>
</head>
<body>
<?php $x=10; ?> <!-- it's as if the jQuery code is executing before this line of code -->
<div id="test1">
Some Text<br/>
<span>replace_this_with_server_response</span>
<br/>
<input type="submit" id ="Update_variable" value="Update">
</div> <!-- end test1 -->
</body>
server_response.php代码:
<?php
sleep(1);
echo 'test_variable = '.$_GET['test_variable'];
?>
您收到错误,因为$x
在脚本中的该点上是未定义的。PHP从上到下处理页面。为了演示,此代码将抛出一个错误:
<?php
echo $x;
$x = 10;
?>
但这个代码会起作用:
<?php
$x = 10;
echo $x;
?>
这与jQuery无关。您可以通过将javascript放在页面底部,或者至少放在$x = 10;
行之后来解决这个特定的问题。
所有php代码都在服务器端执行。所有javascript代码都在客户端执行。
因此,服务器正在读取:
var test_php_variable = <?php echo $x; ?> ;
<?php $x = 10; ?>
并发送
var test_php_variable = undefined ;
到浏览器。
如果改为:
<?php $x = 10; ?>
var test_php_variable = <?php echo $x; ?> ;
服务器将发送
var test_php_variable = 10 ;
到浏览器。
尝试在Charles 这样的工具中查看服务器响应
PHP在服务器上进行处理。它在任何方面都不依赖于JQuery(JQuery是在浏览器中处理的)。对于PHP解释器,代码如下:
blah blah
<?php echo $x; ?>
blah blah
<?php $x=10; ?>
blah blah
现在很明显,您在定义其值之前先阅读$x
。