使用$ .post()中的数据刷新页面

时间:2014-03-31 18:04:14

标签: javascript php jquery

我正在尝试在点击该页面上的链接时将数据发送到索引页面。 index.php页面如下所示:

include "../app/bootstrap.php";
include ("../src/controllers/DisplayContentsController.php");

$data = new DisplayContentsController();
$link = (isset($_POST['link']) ? $_POST['link'] : null);

if ($link != null)
{
    $data->show($twig, $starting_file_path . '/' . $link);
    $starting_file_path = $starting_file_path . '/' . $link;
}
else
{
    $data->show($twig, $starting_file_path);
}

并且在加载的Twig模板上我有这个:

<script>
    jQuery('.show_content').click(function(e)
    {
        e.preventDefault();

        var href = jQuery(this).attr('href');
        jQuery.post(window.location, { link: href });
    });
</script>

我想用新链接重新加载页面,因为它加载了正确的目录。但是当我执行jQuery.post()时,显示的内容不会改变。有人可以帮助我找出问题所在以及如何实现这个目标吗?

1 个答案:

答案 0 :(得分:1)

POST请求的输出将在成功处理函数上返回。例如,您需要执行以下操作:

jQuery('.show_content').click(function(e)
{
    e.preventDefault();

    var href = jQuery(this).attr('href');
    jQuery.post(window.location, { link: href } , function(data){
       //data will have the new HTML after the page posted back. You can use that
       //HTML to load if onto an element on the page. Something like:
       $('#content_result').html(data);           
    });
});

假设你有一个div&#34; id = content_result&#34; - 或类似的东西 - 你可以用它来加载HTML。

如果您想将结果附加到#content_result中已显示的现有HTML,那么只需执行以下操作:

 $('#content_result').html($('#content_result').html()+data);

现在,请记住,这将返回所有内容 - 整个页面 - 如果您盲目地继续附加内容,那么您最终会得到一个不符合有效HTML的页面 - 例如,一个页面超过1个<head><body>部分等。最好的办法是提取您真正关心的部分,并仅附加该部分,以便始终使用有效的HTML文档。

jQuery提供了很多选项来完成这类工作。

相关问题