0

所以这是问题所在,我有一个index.php(包含所有 php 代码)并且我有一个index.tpl包含所有 html 内容的文件。但现在因为我使用 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 文件,然后使用该值并从数据库中提取一些数据。

数据.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 中访问(名称显示在 db 中),但由于 data.php 中的显示功能,整个内容再次显示。

4

3 回答 3

1

用于$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');了一次太多。要找到确切的位置,我必须查看您的来源。请发布文件或有问题的位。

无论如何祝你好运:)

于 2012-08-29T20:38:43.993 回答
1

不知道这是否有帮助。但您也可以将“渲染”的 tpl 返回到您的 AJAX。显示功能通常用于页面的框架。(有点像所有东西的基本占位符)。并与页面刷新一起使用,而不是 AJAX。

在 data.php 中,您可以使用

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

在此之前,您可以在 Smarty 中进行所需的分配。

然后,在 AJAX 中,您可以将返回的 HTML 片段放置在正确的位置。

于 2012-11-06T02:05:39.113 回答
0

我不明白你为什么用ajax重新加载整个页面。如果改变的数据是一个列表,你不能为那个列表创建一个模板吗?所以...

索引.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');
于 2015-09-10T10:11:36.197 回答