简体   繁体   English

在jQuery脚本中调用时,PHP变量为空

[英]PHP variable is empty when called in jQuery script

I'm having a little trouble calling a PHP variable into a jQuery script. 我在将PHP变量调用到jQuery脚本时遇到了一些麻烦。 Basically, I run a few functions to determine if a user is logged in and, if so, store that as $loggedin=1. 基本上,我运行一些函数来确定用户是否已登录,如果已登录,则将其存储为$ loggedin = 1。 If a person that is on a page is NOT logged in, when a button is clicked I want them to be prompted to sign in (I'll obviously still ensure the user is ACTUALLY logged in on the server side before any processing of data). 如果页面上的人未登录,则单击按钮时,我希望提示他们登录(显然,我将确保用户在任何数据处理之前都已经在服务器端正确登录) 。 I searched around, and found the easiest way to get that information over to jQuery is to create the script as a PHP file so I can echo it into the script. 我四处搜索,发现将信息传递到jQuery的最简单方法是将脚本创建为PHP文件,以便可以将其回显到脚本中。 Here is the high level code I'm using: 这是我正在使用的高级代码:

Call up the script: 调用脚本:

<?php
 $loggedIn = 1;
 <script src="../buttonScript.php"></script>
?>

Script: 脚本:

<?php header("Content-type: application/javascript"); ?>
var buttonScript = function(){
 var loggedIn = <?php if($loggedIn===1){echo "1";}else{echo "0";} ?>;
  $("#button").click(function(){
  alert(loggedIn);
 });
};

$(document).ready(buttonScript);

When I click the button in a situation where $loggedIn is equal to 1, the alert gives me 0. In fact, if I simply echo $loggedIn in the script itself, the value is completely empty and the script errors out and won't pop up an alert at all. 在$ loggedIn等于1的情况下单击按钮时,警报给我0。实际上,如果我只是在脚本本身中回显$ loggedIn,则该值将完全为空,并且脚本错误并不会弹出一个警报。 I'm confident that the PHP variable $loggedIn actually has a variable, since if I echo the variable right before the script is called, I successfully see the number 1. What am I missing here? 我相信PHP变量$ loggedIn实际上具有一个变量,因为如果在调用脚本之前立即回显该变量,那么我会成功看到数字1。

Note: added a couple lines in the script calling just for clarity. 注意:在脚本中添加了几行,只是为了清楚起见。

Try this 尝试这个

<?php
 $loggedIn = 1;
 require("/path/buttonScript.php");
?>

buttonScript.php buttonScript.php

<script type="text/javascript">
 var buttonScript = function(){
 var loggedIn = <?php echo $loggedIn; ?>;
  $("#button").click(function(){
  alert(loggedIn);
 });
};

$(document).ready(buttonScript);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM