在通过jQuery加载的PHP中使用全局变量
I am using a jquery function to call a getdata.php file like this -
$("#tasks").load("getdata.php?choice=" + $("#projects").val());
The getdata.php echoes back results dynamically to the callee.
<?php //getdata.php
global $user_id; //<--These variables are defined in the callee file
global $con;
$choice=$_GET['choice'];
$query="SELECT task_id,title from tasks where user_id=$user_id AND proj_id=$choice";
$result=mysqli_query($con,$query) or die(mysqli_error($con));
if((mysqli_num_rows($res))!=0)
{
while (list($task_id, $title) = mysqli_fetch_row($result))
{
echo "<option value=$task_id>$title</option>";
}
}
else
{
echo "<option>No current Tasks</option>";
} ?>
Is there any way by which I can access the variables in the callee file from here. I tried using global as would normally be the case with included files but that's not working here.
我使用jquery函数来调用这样的getdata.php文件 - p>
$(“#tasks”)。load(“getdata.php?choice =”+ $(“#projects”)。val());
code> pre>
getdata.php将结果动态回传给被调用者。 p>
&lt;?php //getdata.php
global $ user_id; //&lt; - 这些变量在被调用者文件中定义
global $ con;
$ choice = $ _ GET ['choice'];
$ query =“SELECT task_id,来自任务的标题user_id = $ user_id AND proj_id = $ choice“;
$ result = mysqli_query($ con,$ query)或die(mysqli_error($ con));
if((mysqli_num_rows($ res))!= 0)
{
while(list($ task_id,$ title)= mysqli_fetch_row($ result))
{
echo“&lt; option value = $ task_id&gt; $ title&lt; / option&gt;”;
}
}
其他
{
echo“&lt;选项&gt;没有当前任务&lt; /选项&gt;”;
}?&gt;
code> pre>
有没有办法可以从这里访问被调用文件中的变量。 我尝试使用全局,因为通常情况下包含文件,但这不起作用。 p>
div>
You may consider using $_SESSION variables to set variables that are available to both your callee file and getdata.php.
Why not put them in the request ? `Something like
$("#tasks").load("getdata.php?choice=" + $("#projects").val() + "&user_id=" + user_id;
(How to pass PHP variables to js as already got a lot of answers on SO)
then in getdata.php
$user_id = $_GET['user_id'];
for the DB connection, you can create a kind of config file that you include on every script
config.php
function getDBConnection() {
blah...blah ...
return $con;
}
in getdata.php as in every script that need it :
require_once yourpath/config.php;
$con = getDBConnection();
For security reasons, if your config file contains passwords, login , etc ... put it outside your web directory.