douzhulan1815 2014-03-31 18:04
浏览 134
已采纳

使用$ .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 2014-03-31 18:08
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致