繁体   English   中英

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

[英]load contents without reloading the page

我正在使用以下代码来加载内容而不加载页面!

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操作地址栏中显示的网址。 然后,您需要在重新加载后从服务器返回正确的数据。

这是设计使然。 重新加载按钮将真正重新加载页面-这包括重置页面状态。

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

常见的工作方法是将所选类别存储在Cookie中,在页面初始化后自动触发类别加载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM