如何从同一div中的外部页面加载链接

Need help..

I have an index.php page. On that page, I have a link to page-2.php.

On page-2.php,

i also have a link to other page. May I know how to load the link on page-2.php in a same div on index.php page.

I'm using jQuery load method do to this. I'm able to load page-2.php inside a div on index.php. Below are the codes that I made.

$(document).ready(function() {
 $('a#staff_info').click(function(e){ //link to page-2.php
  e.preventDefault();
  var page = $(this).attr('href');
  $('#content').load(page);
  $('a#upd_staff').click(function(){ //link on page2.php 
     var page_info = $('a#upd_staff').attr('href');
     $('#content').load(page_info);
  });   
 }); 
});

the above code will direct me to a new page not on a same div

Ajax is asynchronous.

$('#content').load(page);

The above starts loading page two

$('a#upd_staff').click(function(){ //link on page2.php 

Then you try to bind your event handler to content from page 2 before it is has finished loading.

So when you click on the link, there is no JS bound to it, so it acts as a normal link.


Use deferred event handlers (so they listen on the document and check what element was clicked when the click happens).

$(document).ready(function() {
    function ajaxLoad(event) {
        event.preventDefault();
        var page = $(this).attr('href');
        $('#content').load(page);       
    }
    $(document).on("click", "a#staff_info, a#upd_staff", ajaxLoad);
 });

You can use get() for add directly on your div:

$(document).ready(function() {
 $('a#staff_info').click(function(e){ //link to page-2.php
  e.preventDefault();
  var page = $(this).attr('href');
  $.get(page, function(data, status){
    //action on page loaded, data is your page result
     $('#content').html(data)
  });
  $('a#upd_staff').click(function(){ //link on page2.php 
     var page_info = $('a#upd_staff').attr('href');
     $('#content').load(page_info);
  });   
 }); 
});

when you click on $('a#staff_info') this -- I can see that you use e.preventDefault(); for preventing the normal action of the anchor tag but when you click on $('a#upd_staff') this you did not use e.preventDefault(); -- that's why this redirect to page2.php. Use e.preventDefault(); - this for next one click may be this will help you