2016-07-21 58 views
0

我做了一個ajax函數,它在我的index.php中的ajax-container div內調用我的html頁面,所以現在我怎麼做,如果我也想調用php頁面在Ajax?用Ajax調用html和php頁面

有我的代碼:

htaccess的重寫

Options +FollowSymLinks 
RewriteEngine On 
RewriteBase/
RewriteRule ^([a-zA-Z0-9\-]*).html$ index.php?p=$1 [L] 

的index.php

<div class="link" href="page2.html">go html</div> 
 
<div class="link" href="page3.php">go php</div> 
 

 
<div id="ajax-container"> 
 
     <?php 
 
$d = "pages/"; 
 

 
if (isset($_GET['p'])) 
 
\t { 
 
\t $p = strtolower($_GET['p']); 
 
\t if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".html")) 
 
\t \t { 
 
\t \t include $d . $p . ".html"; 
 

 
\t \t } 
 
\t else 
 
\t \t { 
 
\t \t include $d . "404.html"; 
 

 
\t \t } 
 
\t } 
 
    else 
 
\t { 
 
\t include $d . "home.html"; 
 

 
\t } ?> 
 
</div>

這是我AJAX功能調用從文件夾中的網頁HTML頁/

var afficher = function(data, page) { 
 

 
    $('#ajax-container').fadeOut(100, function() { 
 
     $('#ajax-container').empty(); 
 
     $('#ajax-container').append(data); 
 
     $('#ajax-container').fadeIn(100, function() {}); 
 
    }); 
 
}; 
 

 
var lastRequest = null; 
 
if (lastRequest !== null) { 
 
    lastRequest.abort(); 
 
} 
 

 
var loadPage = function(page, storeHistory) { 
 
    if (typeof storeHistory === 'undefined') { 
 
     storeHistory = true; 
 
    } 
 

 

 
    lastRequest = $.ajax({ 
 
     url: 'pages/' + page, 
 
     cache: false, 
 
     success: function(html) { 
 
      afficher(html, page); 
 
      if (storeHistory === true) { 
 
       history.pushState({ 
 
        'key': 'value', 
 
        'url': page 
 
       }, '', page); 
 
      } 
 
     }, 
 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
 
      afficher('erreur lors du chagement de la page'); 
 
     } 
 
    }); 
 

 
    return false; 
 
}; 
 

 
window.addEventListener('load', function() { 
 
    setTimeout(function() { 
 
     window.addEventListener('popstate', function(e) { 
 
      if (e.state === null) { 
 
       loadPage('home.html'); 
 
      } else { 
 
       loadPage(e['state']['url'], false); 
 
      } 
 
     }); 
 
    }, 0); 
 
}); 
 

 
$(document).ready(function() { 
 
    
 
    $('.link').bind('click', function(e) { 
 
    e.preventDefault(); 
 
    var page = $(this).attr('href'); 
 
    loadPage(page); 
 
    return false; 
 
    }); 
 
    
 
});

回答

1

如果要執行PHP,並顯示它返回什麼你可以使用jQuery和AJAX一個div:

$(function(){ 
    $(".myDivClass").load('yourPHPFile.php'); 
}()); 
+0

謝謝你的工作,但我怎樣才能使用它爲我的popstate功能? – Tiaw

+0

把它放在'loadPage('home.html');'在你的代碼中應該可以工作。那就是如果我明白你的問題:P。不要忘了提出答案,並將其標記爲答案,如果這樣做的話:D @Tiaw –