2013-06-26 112 views
0

我有一個包含許多PHP include語句的html頁面。 其中一個需要較長時間才能加載。但我想要其餘的元素得到更早加載,但想要保持序列在加載剩餘頁面內容後加載頁面的一部分

index.php 
<div id="a1"> 
<? include('a.php'); ?> 
</div> 
<div id="b1"> 
<? include('b.php'); ?> 
</div> 
<div id="c1"> 
<? include('c.php'); ?> 
</div> 

我想要保持相同的序列。 b.php需要較長時間才能加載,最終影響整個頁面的加載。 我想先加載a.php和c.php,然後再加載b.php。 如何使用AJAX做同樣的事情?

+0

PHP在服務器端執行,所以執行是真的'fast' ..我更喜歡檢查哪個代碼塊在b.php....上花費了很多時間,而不是尋找jQuery/AJAX解決方案 – swapnesh

回答

0

您可以使用jQuery​​到其他頁面加載到您的HTML頁面

<div id="a1"> 
<? include('a.php'); ?> 
</div> 
<div id="b1"> 

</div> 
<div id="c1"> 
<? include('c.php'); ?> 
</div> 

<script type='text/javascript'> 
    $(document).ready(function (e) { 
     $('#b1').load('/path/to/b.php'); 
    }); 
</script> 
0
<script> 
    $(function(){ 
     $('#a1').load('a.php'); 
     $('#b1').load('b.php'); 
     $('#c1').load('c.php'); 
    }); 
</script> 
<div id="a1"> 
<? include('a.php'); ?> 
</div> 
<div id="b1"> 
<? include('b.php'); ?> 
</div> 
<div id="c1"> 
<? include('c.php'); ?> 
</div> 

包含的jquery.js withing你的腳本,如果它不存在。之前

0
<? 
$a=false; 
$b=false; 
$c=false; 
?> 
<div id="a1"> 
<? $a = include('a.php'); ?> 
</div> 
<div id="c1"> 
<? $c = include('c.php'); ?> 
</div> 

<? if ($a && $c) { ?> 
<div id="b1"> 
<? include('b.php'); ?> 
</div> 
<? } ?> 

然後使用JavaScript,如果你想具體定位

0

的index.php

<div id="a1"> </div> 
<div id="b1"> </div> 
<div id="c1"> </div> 


<script> 
(function() { 
function ajax(location, element){ 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
    if(xhr.readyState == 4 && xhr.status == 200) { 
     element.innerHTML = xhr.responseText; 
     return true; 
    }; 
    } 

    xhr.open("GET", location, true); 
    xhr.send(); 
    } 
    if(true) { 
    var a = document.getElementById('a1'); 
    var b = document.getElementById('b1'); 
    var c = document.getElementById('c1'); 
    if(ajax('/a.php', a) && ajax('/c.php', c)) { 
     ajax('/b.php', b); 
    } 
    } 
    })(); 
</script> 
0
<script type="text/javascript"> 
    $(function() { 
    $('#a1').load('a.php', function() { 
     $('#c1').load('c.php', function() { 
     $('#b1').load('b.php'); 
     }); 
    }); 
    }); 
</script>