2016-12-04 79 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