加载内容而不重新加载页面

load contents without reloading the page

本文关键字:加载 新加载      更新时间:2023-09-26

我使用以下代码,用于加载内容而不加载页面!

index . html

<html>
    <head>
        <script type="text/javascript">
            // <![CDATA[
            document.observe('dom:loaded', function () {
                    var newsCat = document.getElementsByClassName('newsCat');
                    for(var i = 0; i < newsCat.length; i++) {
                        $(newsCat[i].id).onclick = function () {
                            getCatPage(this.id);
                        }
                    }
                });
            function getCatPage(id) {
                var url = 'load-content.php';
                var rand = Math.random(9999);
                var pars = 'id=' + id + '&rand=' + rand;
                var myAjax = new Ajax.Request(url, {
                        method: 'get',
                        parameters: pars,
                        onLoading: showLoad,
                        onComplete: showResponse
                    });
            }
            function showLoad() {
                $('newsContent').style.display = 'none';
                $('newsLoading').style.display = 'block';
            }
            function showResponse(originalRequest) {
                var newData = originalRequest.responseText;
                $('newsLoading').style.display = 'none';
                $('newsContent').style.display = 'block';
                $('newsContent').innerHTML = newData;
            }
             // ]]>
        </script>
    </head>
    <body>
        <div class="newsCat" id="newsCat1">Politics</div>
        <div class="newsCat" id="newsCat2">Sports</div>
        <div class="newsCat" id="newsCat3">Lifestyle</div>
        <div id="newsLoading">Loading
            <img src="loading_indicator.gif" title="Loading..." alt="Loading..." border="0" />
        </div>
        <div id="newsContent"></div>
        </div>
    </body>
</html>

此页用于在index.php中包含所需的页面!

content-load.php

<?php
function stringForJavascript($in_string) {
$str = preg_replace("# ['r'n] #", " ''n'''n", $in_string);
$str = preg_replace('#"#', '''"', $str);
return $str;
$user = $_SESSION['userName'];
}
switch($_GET['id']) {
    case 'newsCat1':
    $content = include("politics.php");
    break;
case 'newsCat2':
    $content = include("sports.php");
    break;
case 'newsCat3':
    $content = include("lifestyle.php");
    break;
default:
    $content = 'There was an error.';
} 
print stringForJavascript($content);
usleep(600000);
?>

面临的问题

它工作得很好,但当我刷新页面或提交表单时,代码刷新,我的意思是在刷新之前包含的页面不存在......

我真的很抱歉我的英语,我知道它很可怕!:)

请帮助我PHP大师,我需要你的帮助…

解决这个问题有两种方法。

您可以在客户端网站上使用当前加载的标签并使用该数据重建页面,或者:
使用pushState API来操作地址栏中显示的url。然后需要在重新加载后从服务器返回正确的数据。

这是设计的行为。Reload按钮将真正重新加载页面——这包括重置页面状态。

在新加载的页面中,您不显示类别-这仅在页面完成加载后由用户交互触发。

一种常见的解决方法是将选择的类别存储在cookie中,在页面初始化后自动触发类别加载