php - 需要一个 html 页面但不回显它

标签 php javascript html ajax

我正在使用 json 和 AJAX,以便在不刷新页面的情况下获取一些 HTML。 AJAX 调用调用一个简化的函数是这样的:

function postHTML($post) { // returns the HTML structure for a post starting from an array of variables
    # other stuff
    require('post.template.php'); // which is mostly HTML with just few php variables embedded
}

$data = '';
foreach ($posts as $post) {
    $data .= postHTML($post);
}

之后我按如下方式管理 json:

echo json_encode(array('success' => true, 'data' => $data));

其中数据应该是加载的每个帖子的 HTML 结构。 问题是当我需要 'post.template.php' 文件时,它使用 require 并将数据返回给 Javascript:

[HTML posts] {"success": true, "data": ""}

我怎样才能将 HTML 放入一个变量中,然后将其传递给 json_encode 而实际上不需要页面(仍应作为 PHP 执行)?

最佳答案

您可以使用 Output buffering , around your require, to capture the output, preventing it from being echoed : it'll get stored in memory, and you'll able to fetch it to a variable.


基本上,这意味着使用以下类型的代码:

ob_start();

// Output is no longer sent to the standard output,
// but stored in memory
require('post.template.php');

// Fetch the content that has been stored in memory
$content = ob_get_clean();


作为引用:

关于php - 需要一个 html 页面但不回显它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5343484/

相关文章:

javascript - 递归地将数组元素放入自己的数组中

html - 使用 CSS 更改跨度背景颜色无效

javascript - 仅将 Canvas 的一部分转移到新 Canvas

php - SELECT 语句不能正常工作

php - 在 Symfony2 中处理类 CMS 项目路由的最佳方法是什么

php - MSSQL PHP 无法删除行

javascript - 将事件绑定(bind)到 jQuery Modal Pop Up 中动态添加的元素

php - 在 Kohana PHP 框架中启用 PECL HTTP

javascript - 初学者 JavaScript : using src

html - 链接前的插入符号