需要一个html页面但不回应它

时间:2011-03-17 18:24:20

标签: 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执行)?

3 个答案:

答案 0 :(得分:3)

你可以使用你需要的Output buffering来捕获输出,防止它被回显:它将被存储在内存中,你将能够将它提取到一个变量。


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

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();


作为几个参考:

答案 1 :(得分:2)

<?php

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

    return $output;
}

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

答案 2 :(得分:0)

将所有数据生成代码放在另一个函数中,并在必要时调用它。 (是的,PHP中允许使用嵌套函数,但由于您使用'require',因此不能确定这适用于您的情况。)