2012-08-29 197 views
0

所以這裏是問題,我有一個index.php(與所有的PHP代碼),我有一個index.tpl文件與所有的HTML的東西。但現在因爲我使用ajax,我有另一個PHP文件,應該輸出一些數據(data.php)。問題是我不知道如何選擇data.php文件中的模板,我所知道的只是index.php我有一個顯示tpl ($Smarty->display($filename);的函數),但我不想再次顯示模板,在data.php文件我只想分配一些變量需要顯示在index.tplsmarty模板

編輯:

確定這將是很長: 首先我需要解釋我想實現的目標。我有index.php和data.php。在index.php:

<?php 
include("../include/config.php"); 
include("../include/functions/import.php"); 

$thebaseurl = $config['baseurl']; 

    $query ="SELECT name FROM contacts"; 
    $results = $conn->execute($query); 
    $select-names = $results->getrows(); 
    STemplate::assign('select-names',$select-names); 

$templateselect = "index.tpl"; 
STemplate::display($templateselect); 
?> 

的index.tpl裏是有點長,所以我會發布重要組成部分:

xmlhttp.open("get","data.php?q="+str,true); 

這是AJAX代碼,該代碼發送+ STR值GET方法data.php文件然後使用該值並從數據庫中提取一些數據。

data.php:

$q=$_GET["q"]; 

$sql="SELECT * FROM contacts WHERE name = '$q'"; 

$result = mysql_query($sql); 


while($row = mysql_fetch_array($result)) 
    { 
    $name = $row['name']; 
    } 

STemplate::assign('name',$name); 
$templateselect = "index.tpl"; 
STemplate::display($templateselect); //the second display 
?> 

我使用該類這裏STemplate的Smarty的功能,但你得到的是代碼。

我希望你明白現在有什麼問題。如何在不顯示模板文件的情況下將變量分配給模板。這樣,$ name變量可以在index.tpl中找到(名稱顯示在數據庫中),但由於data.php中的顯示函數,整個內容會再次顯示。

+0

要麼我誤會提出這個問題或者你問的問題是不可能的。你想讓ajax調用data.php刷新顯示的頁面?內容如何顯示兩次?請顯示您的JavaScript代碼。 – Alfwed

回答

1

使用$smarty->assign('var', 'value');來分配值。

欲瞭解更多信息更多信息here

編輯

.tpl背後的想法是進入使用assign變量,當頁面就緒顯示器使用它display。您可以顯示之前設置多個變量:

<?php 

$smarty = new Smarty(); 

$smarty->assign('firstname', 'Doug'); 
$smarty->assign('lastname', 'Evans'); 
$smarty->assign('meetingPlace', 'New York'); 

$smarty->display('index.tpl'); 

?> 

如果你看到文本的兩倍,這意味着在某個地方你打電話$smarty->display('index.tpl');一次太多。準確找到我需要查看您的來源的位置。請張貼文件或有問題的位。

好運無論如何:)

+0

謝謝你的鏈接。有些事情現在很清楚。但我仍然有問題。分配工作正常,但前提是$ smarty-> display('index.tpl');問題是如果我把這一行放在data.php和index.php中,整個內容會顯示兩次。 –

+0

@VladimirSabo回答已更新。 – Kuf

+0

Hi @VladimirSabo,如果這有幫助,請[接受此答案](http://meta.stackexchange.com/questions/16721/how-does-accept-rate-work/65088#65088) – Kuf

1

不知道這是否有幫助。但您也可以將「呈現」的tpl返回給您的AJAX。顯示功能通常用於頁面的框架。 (有點像一切的基本佔位符)。並用於頁面刷新,而不是AJAX。

在data.php你可以使用

$answer = $smarty->fetch("ajaxreturn.tpl"); 
echo $answer; 
die(); 

在這之前,你可以做必要的受讓人在Smarty的。

在AJAX中,您可以將返回的HTML片段放在正確的位置。

0

我不明白你爲什麼用ajax重新加載整個頁面。如果更改的數據是一個列表,你不能只爲該列表創建一個模板嗎?所以......

在index.tpl

<body> 
... content ... 
<div id="ajax_list"> 
{include file="data.tpl"} 
</div> 
... content ... 
</body> 

,然後在data.tpl

<ul> 
{foreach $rows as $row} 
<li>{$row.name}</li> 
{foreach} 
</ul> 

你進入第一次index.php的,它將使雙方在index.tpl和data.tpl ,然後你只需要添加JavaScript代碼刷新#ajax_list內容與data.php,這將只處理data.tpl與

$smarty->display('data.tpl');