简体   繁体   中英

Dynamic page update by AJAX

I've got a problem.

I'm using AJAX to load pages and it works correctly, but I can't escape a bug.
When I load page, first time it works correctly but then I go to another page, AJAX loads the page I want, but it has double tags like <head> and <footer> .

I mean when I load page a second time, the page loads the same page in <div> . It's like picture in picture.

I use in templates code like this:

<?php echo $header ?>
            My content
<?php echo $footer ?>

And every page load the same code after I get back to previous page by link.

My ajax code:

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; }
        }
    }
}

What Can I do? Because if I delete Tags header and footer my page doesn't have design at all. And as u see, I change URL (important for me).

I need solution which will help me load templates without double-tagging.

In your template, be sure that you have something like

<?php echo $header ?>
        <div id="content">My content</div>
<?php echo $footer ?>

And that id="content" is unique, only there and not in your $header or $footer.

If the pages you're pulling in with the JavaScript XHR (Ajax) also contain the PHP header and footer code, then you'll need to replace those also with your XHR:

<div id="content">
<?php echo $header ?>
My content
<?php echo $footer ?>
</div>

Wrap your content div tag around the header and footer in order to overwrite them rather than duplicate them.


Alternatively, the way I've implemented a PHP template system is like this:

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>

Everything goes to the index.php file. You can use PHP to block direct access to page files, or if using Apache web server you can use .htaccess to redirect all requests to the index.php file.

The technical URL looks like http://example.net/index.php?page=samplepage.html . But, using .htaccess can be effectively converted to http://example.net/samplepage.html with:

RewriteRule ^(.*)$ index.php?page=$1&%{QUERY_STRING} [L]

This can happen if you are not clearing the previous content and the new content is being " appended " to the existing DOM.

So following points could be your solution.

  1. In each ajax call, before updating the container element, clear the existing element, eg. cont.innerHTML = '';
  2. Remember to keep track of any event bindings that are coming with the incoming response.
  3. Move this line var cont = document.getElementById('content'); inside the ajax call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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