如何在不重新加载网页的情况下更改div的内容?

时间:2011-03-15 18:46:51

标签: php javascript jquery ajax

我有一个网站,它使用PHP来选择内容,

<div>  
    <? include ("navigation.php"); // navigation.php generates the menu ?>
</div>
<div>
    <?      
        $type = $_GET["type"];
        switch ($type) {
        case "page" :
            include "Text.php";
            break;  
        case "news":
            include "news_2.php";
            break;
        default :
            include "main.php";     
        }
    ?>
</div>

网址格式为domain.com/index.php?type。 我需要更改块#content而不重新加载整个页面,我该怎么做?

3 个答案:

答案 0 :(得分:4)

当您使用“jquery”标记问题时,我假设您知道这是什么,并且您将其加载到页面中。

你需要的就是给你的div和ID ......这里的内容

然后使用一些jquery ..最简单的形式,只是在页面加载完成后将你的内容从'myurl.php'加载到'mydiv':

$(document).ready(function() { 
  $("#mydiv").load("myurl.php");
});

毫无疑问,您需要一些逻辑来确定负载以及在什么情况下。如果您需要将数据传回URL,则需要使用jquery ajax($ .ajax)。它非常简单,网上有大量的例子,还有JQuery网站上的优秀文档。

答案 1 :(得分:1)

这最好用Ajax完成。我喜欢使用jQuery的ajax函数。像这样:

function load(page){    
    var datastring='ANY DATA YOU WANT TO SEND';

    $.ajax({
        type: "POST",
        url: 'your/pagehtml/',
        data: "bust="+Date()+datastring,
        dataType: "html",
        cache: false,
        success: function(html){ 
            $('#content').html(html)
        }
    });
    return false;
}

您不需要以这种方式在网址中发送网页。无论何时更改网址,您都必须加载其他网页。在.htaccess之外重写。这不是你需要的。

点击或根据需要点击此消息。

答案 2 :(得分:0)

如果你正在使用jQuery,那很简单。您没有发布应该触发更改的内容,因此我假设您在其他元素中有一个链接列表,其ID为nav。

在此处阅读有关jQuery Ajax请求的更多信息:http://api.jquery.com/jQuery.ajax/

//run on page load
$(function(){   
    //bind a click event to the nav links
    $("#nav a").bind("click", function(e){ 

        //keep the links from going to another page by preventing their default behavior
        e.preventDefault();

        //this = link; grab the url
        var pageLocation = this.href;

        //fire off an ajax request
        $.ajax({ 
            url: pageLocation, 

            //on success, set the html to the responsetext
            success: function(data){ 
                $("#content").html(data.responseText); 
            } 
        });
    });
});

我还建议做一些代码清理,比如在load事件上缓存你的$(“#content”)元素(比如window.container = $(“#container”),稍后再使用window.container) ,但我把它保持原样,以便一切都清晰。

相关问题