2016-12-04 80 views
1

试图早些时候问这个问题,但总是把它弄得一团糟。所以我想我会再试一次,但这一次更清晰。如何使php变量显示在加载的内容

你怎么能得到PHP变量显示在使用JQuery加载的内容?

的index.php:

<!doctype html> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Untitled Document</title> 
<script> 
$(document).ready(function(){ 
    $('#clickMe').click(function(){ 
     $('#parent').load('loaded.php #child', {},function(){ 

    }); 

     }); 

}); 
</script> 
</head> 
<?php 
session_start(); 
$test = "this should display php string"; 
$_SESSION['another'] = "Session variable String"; 

echo ' tests to see if they work below <br>'; 
echo $test."<br>"; 
echo $_SESSION['another']."<br><br>"; 
?> 
<button name="clickMe" id="clickMe" class="clickMe">Click me</button> 
<div class="parent" name="parent" id="parent" style="background-color:yellow; height:200px; width:200px;"> 
</div> 
<body> 
</body> 
</html> 

loaded.php:

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Untitled Document</title> 
</head> 

<body> 
    <div name="child" id="child" class="child"> 

      <p1> html loads fine..</p1><br> 
     <?php echo $test ?><br> 
     <?php echo $_SESSION['another'] ?> 
    </div> 
</body> 
</html> 
+3

启动会话并定义变量 –

+0

需要从URL中删除'#child'。如果你想要一些特定的返回值,请在请求中使用一个参数,并让请求页面只提供该位。关闭'head'之后还应该有''。 – chris85

+0

nocked这个快速,生病尝试这些消化有点当im免费:) – bodovix

回答

1

如前所述通过@Fred -ii-在评论中,你只需要在你的index.php获取会话文件来做到这一点。

如果你想进去的index.php另一个网页的一部分:

index.php应该包含这个调用:

$(document).ready(function(){ 
    $('#clickMe').click(function(){ 
     $('#parent').load('loaded.php'); // No need for additional parameters 
    }); 
}); 

你并不需要选择HTML的一部分,仅返回你所需要的:

loaded.php

<?php session_start() ?> 
<p>Example text</p> 
<?php echo $_SESSION['another'] ?> 
+0

在主要项目即时通讯使用此病在发送选定部分的loaded.php页面,索引页(不同的形式来填充父母根据需要...) – bodovix

+1

你的权利,虽然把session_start放在加载页面的一部分,我需要似乎做的伎俩,谢谢!一旦你知道它,再一次解决方案是非常明显的! – bodovix

+0

这个效果很好,但它对于非会话变量会有什么不同? - 只是为了完成学习? – bodovix