所以问题来了,我有一个index.php
(包含所有php代码)和一个包含所有html内容的index.tpl
文件。但现在因为我使用ajax,我有另一个php文件应该输出一些数据(data.php)。问题是我不知道如何在data.php文件中选择模板,我只知道在index.php
上我有一个显示tpl ($Smarty->display($filename);
的函数,但我不想在data.php
文件中再次显示模板。我只想分配一些需要在index.tpl
上显示的变量
编辑:
好吧,这会很长:首先,我需要解释一下我想完成什么。我有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代码,该代码将GET方法中的+str值发送到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中的dispally函数,整个内容将再次显示。
使用$smarty->assign('var', 'value');
分配值。
欲了解更多信息,请点击此处阅读更多信息。
编辑
.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');
的次数太多了。为了找到确切的位置,我必须找到你的消息来源。请张贴文件或有问题的部分。
祝你好运:)
不知道这是否有帮助。但是您也可以将"rendered"tpl返回到AJAX。显示功能通常用于页面的边框。(有点像所有内容的基本占位符)。并且用于页面刷新,而不是AJAX。
在data.php中,您可以使用
$answer = $smarty->fetch("ajaxreturn.tpl");
echo $answer;
die();
在此之前,您可以在Smarty中完成所需的分配。
在AJAX中,您可以将返回的HTML片段放在正确的位置。
我不明白为什么要用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代码来用data.php刷新#ajax_list内容,这将只使用处理data.tpl
$smarty->display('data.tpl');