简体   繁体   中英

Loading PHP file into DIV via AJAX

Say I have an index.php that loads a page.php into the div of class ' wrapper '.

page.php in turn has its own links and I want it so that when you click on one of these links it loads the respective page into the SAME ' wrapper ' div .

Similarly that loaded page might have its own links and I want to continue loading content into the same div. How might I achieve this chain effect of pages?

jQuery / AJAX is your friend here:

$('#link').click(function() {
        var go = $.ajax({
            type: 'POST',
            data: {m: 'ajax', // POST Variables go here...
                linkID: $(this).val()} // $(this).val() is the value of the link clicked
        })
        .done(function(results) {
            $('#resultsDiv').html(results); // This is where your results go
        })
        .fail(function(msg) {
            alert("Error:" + msg);
        })
        .always(function() {
        });
    }

I would put the AJAX call into a function:

function loadWrapper($url){
    $('#wrapper').load($url+' > *',function(){
        $(this).on('click','a',function(e){
            e.preventDefault();
            loadWrapper($(this).attr('href'));
        });
    });
}

Then on page load assign the click to any item on the page that loads initially:

$('.LinkClass').on('click',function(e){
    e.preventDefault();
    loadWrapper($(this).attr('href'));
});

And, of course, your original load:

loadWrapper('page.php');

The callback in the function will allow click events to fire on the loaded links, as well as any other links you may add in the future you want to load in .Wrapper . Just give those links the class LinkClass (or whatever you want) and you're good to go.

Using jQuery:

var activateLinks = function() {
    $('.wrapper a[href]').click(function(){
        $('.wrapper').load($(this).attr('href'), activateLinks);
        return false;
    });
}

$('.wrapper').load('page.php', activateLinks);

or else

$('.wrapper').on('click', 'a[href]', function() {
    $('.wrapper').load($(this).attr('href');
    return false;
}
$('.wrapper').load('page.php');

Using a delegate is best this way you dont have to run handler attavchment for the links on the new page. They are handled automatically.

$(document).on('click', 'div.wrapper a[href]', 'click', function (e) {
    e.preventDefault();
    $.get($(this).attr('href'), function (html) {
       $('div.wrapper').html(html);
    });
});

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