[英]Dynamic page update by AJAX
我有一個問題。
我正在使用AJAX加載頁面,並且可以正常工作,但是我無法逃脫錯誤。
當我加載頁面時,第一次它可以正常工作,但是隨后我轉到另一個頁面,AJAX加載了我想要的頁面,但是它具有<head>
和<footer>
類的雙標簽。
我的意思是,當我第二次加載頁面時,該頁面會在<div>
加載同一頁面。 就像畫中畫一樣。
我在這樣的模板代碼中使用:
<?php echo $header ?>
My content
<?php echo $footer ?>
通過鏈接返回上一頁后,每個頁面都加載相同的代碼。
我的ajax代碼:
function showContent(link) {
var cont = document.getElementById('content');
var loading = document.getElementById('loading');
window.history.replaceState('', 'Title', link);
cont.innerHTML = loading.innerHTML;
var http = createRequestObject(); // создаем ajax-объект
if( http ) {
http.open('get', link); // инициируем загрузку страницы
http.onreadystatechange = function () { // назначаем асинхронный обработчик события
if(http.readyState == 4) {
cont.innerHTML = http.responseText; // присваиваем содержимое
}
}
http.send(null);
} else {
document.location = link; // если ajax-объект не удается создать, просто перенаправляем на адрес
}
}
// создание ajax объекта
function createRequestObject() {
try { return new XMLHttpRequest() }
catch(e) {
try { return new ActiveXObject('Msxml2.XMLHTTP') }
catch(e) {
try { return new ActiveXObject('Microsoft.XMLHTTP') }
catch(e) { return null; }
}
}
}
我能做什么? 因為如果我刪除標簽頁眉和頁腳,我的頁面根本沒有設計。 如您所見,我更改了URL(對我來說很重要)。
我需要可以幫助我加載模板而不進行雙重標記的解決方案。
在模板中,請確保您有類似
<?php echo $header ?>
<div id="content">My content</div>
<?php echo $footer ?>
而且id="content"
是唯一的,僅在此位置,而不在您的$ header或$ footer中。
如果您使用JavaScript XHR(Ajax)進入的頁面還包含PHP頁眉和頁腳代碼,則需要用XHR替換這些頁面:
<div id="content">
<?php echo $header ?>
My content
<?php echo $footer ?>
</div>
將您的內容div
標簽環繞在頁眉和頁腳上,以便覆蓋它們而不是重復它們。
另外,我實現PHP模板系統的方式如下:
的index.php
<?php
// GET PAGE
if ( isset($_GET['page'])
&& '' != $_GET['page']
&& !preg_match('!^(/|\.|(ht|f)tp://)!', $_GET['page'])
) $page = $_GET['page'];
else $page = 'home.html';
// EXECUTE TEMPLATE
require('template.php');
?>
的template.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<!-- plain HTML header goes here -->
<!-- RETRIEVE PAGE -->
<?php require('pages/' . $page); ?>
<!-- plain HTML footer goes here -->
</body>
</html>
samplepage.html
<h2>Sample Page Header</h2>
<p>Sample page content goes here.</p>
phppage.php
<h2>PHP Page Header</h2>
<p><?php echo 'PHP page content goes here.'; ?></p>
一切都進入index.php文件。 您可以使用PHP阻止直接訪問頁面文件,或者如果使用Apache Web服務器,則可以使用.htaccess將所有請求重定向到index.php文件。
技術網址類似於http://example.net/index.php?page=samplepage.html
。 但是,使用.htaccess可以通過以下方式有效地轉換為http://example.net/samplepage.html
:
RewriteRule ^(.*)$ index.php?page=$1&%{QUERY_STRING} [L]
如果您不清除以前的內容,而新內容被“ appended
”到現有DOM,則會發生這種情況。
因此,以下幾點可能是您的解決方案。
ajax
調用中,在更新容器元素之前,請清除現有元素,例如。 cont.innerHTML = '';
var cont = document.getElementById('content');
在ajax調用中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.