AJAX从PHP后端加载的页面

时间:2014-07-02 20:02:38

标签: javascript php jquery html ajax

我要做的是从不同页面加载信息,而不必刷新整个主页...

您能否告诉我如何调整此代码以加载具有不同名称的文件(例如about.htmlproject.html

注意:此代码仅用于加载'page_.html'个文件。


var default_content="";

$(document).ready(function(){

    checkURL();
    $('ul li a').click(function (e){

            checkURL(this.hash);

    });

    default_content = $('#pageContent').html();


    setInterval("checkURL()",250);

});

var lasturl="";

function checkURL(hash)
{
    if(!hash) hash=window.location.hash;

    if(hash != lasturl)
    {
        lasturl=hash;

        if(hash=="")
        $('#pageContent').html(default_content);

        else
        loadPage(hash);
    }
}


function loadPage(url)
{
    url=url.replace('#page','');

    $('#loading').css('visibility','visible');

    $.ajax({
        type: "POST",
        url: "load_page.php",
        data: 'page='+url,
        dataType: "html",
        success: function(msg){

            if(parseInt(msg)!=0)
            {
                $('#pageContent').html(msg);
                $('#loading').css('visibility','hidden');
            }
        }

    });

}

<小时/> 这是php文件:

if(!$_POST['page']) die("0");

$page = (int)$_POST['page'];

if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');

else echo 'There is no such page!';

2 个答案:

答案 0 :(得分:0)

替换此行

if(file_exists('pages/page_'.$page.'.html'))

用这个

if(file_exists('pages/'.$page.'.html'))

答案 1 :(得分:0)

您可以创建多个ajax请求,这是jquery加载方法:

$( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

做那2倍你的健康! 请记住,这需要jquery库。

我在我的网站上做了类似的事情,这是我的代码:

    window.setInterval("check()",60000); 
//request information notice is inside a function called check() (it's not required to put inside function I only do this if I will be making the same request multiple time throughout the program)                      
                        function check() {
                            var request = $.ajax({
                                url: "file.php",
                                type: "POST",            
                                dataType: "html"
                            });

                            request.done(function(msg) {
//when request is done:
                                $(".wheretoputnewdata").html(msg);          
                            });

                            request.fail(function(jqXHR, textStatus) {
                                //if request failed do this:
    alert( "Request failed: " + textStatus );
                            });
                       }