douzhulan1815
douzhulan1815
2014-03-31 18:04

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

I am trying to send data to a index page when a link on that page is clicked. the index.php page looks like this:

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

and on the Twig template that is loaded I have this:

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

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

I want to reload the page with the new link that way it loads the correct directory. But when I do the jQuery.post() the content that is displayed does not change. Can someone help my find out what is going wrong and how I can accomplish this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • ds1379551 ds1379551 7年前

    The output from the POST request would be returned on the success handler function. For example, you would need to do something like this:

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

    Assuming you have a div with "id = content_result" -or something like that- that you can use to load the HTML into it.

    If you want to append the result to the existing HTML already displayed inside #content_result then simply do:

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

    Now, keep in mind that this will return everything - the full page - and if you blindly keep appending things, you'll end up with a page that does not conform to valid HTML -for example, a page with more than 1 <head>,<body> sections, etc. The best thing to do is to extract the section that you really care about, and append only that section such that you always end up with a valid HTML document.

    jQuery offers plenty of options to do this sort of thing.

    点赞 评论 复制链接分享

为你推荐