ดาวโหลดไฟล์ตัวอย่าง และไฟล์ที่จำเป็นได้ที่
https://www.ninenik.com/download/ajax-cache-page.rar
โค้ดตัวอย่างการใช้งาน
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <?php include ( "cache-kit.php" ); // เรียกใช้ไฟล์ php class $cache_active = true; // กำหนดให้ทำการ cache $cache_folder = 'cache/' ; // กำหนดไฟลเดอร์ที่ไว้เก็บไฟล์ cache ?> <?php $page_cache = acmeCache::fetch( $fullPathFile . $n_browser , 10); // ทำการ cache หน้าเว็บไซต์ใหม่ ไว้ในตัวแปร $page_cache ทุกๆ 10 วินาที สามารถกำหนดเป็นค่าอื่นได้ if (! $page_cache ){ // ตรวจสอบว่าถ้าไม่มีข้อมูลที่ cache ไว้ ให้ทำการเก็บค่า html ไว้สำหรับบันทึก cache ?> <html> <head> <title>Cache Page</title> <style type= "text/css" > ..mysty1{ width:550px; height:200px; background-color:#FFCC66; } </style> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" > </head> <body> <div class = "mysty1" > <p>ตัวอย่างต่อไปนี้เป็นการ cache ไฟล์ทุก 10 วินาที<br> จะทำการ cache หลังจากโหลดหน้าเว็บแล้ว 2 วินาที ด้วย ajax</p> <p>ทดสอบ โดย เมื่อเข้ามาหน้านี้ครั้งแรก จะไม่มีข้อความว่า Cache Data<br> แสดงว่าเป็นการโหลดข้อมูลแบบปกติ ให้รออย่างน้อย 2 วินาที แล้วกด refresh ที่ บราวเซอร์<br> จะแสดงข้อความ Cache Data ใต้กล่องสี่เหลี่ยมสีเหลืองแก่ แสดงว่าเป็นข้อมูลจากการ cache<br> และข้อมูลการ cache จะอยู่นาน 10 วินาที ตามที่กำหนดในตัวอย่าง ซึ่งสามารถกำหนด เป็นจำนวนที่มากๆ ได้ ขึ้นอยู่กับความต้องการแสดงข้อมูลให้เป็นปัจจุบัน</p> </div> <script type= "text/javascript" src= "js/jquery-1.4.2.min.js" ></script> </body> </html> <?php if (!isset( $_POST [ 'genTime' ])){ echo "<script type=" text/javascript ">rn" ; echo "$(function(){rn" ; echo "setTimeout(function(){rn" ; echo "$.post('genCache.php',{nameFile:'" . $fullPathFile . "'});rn" ; echo "},2000);rn" ; echo "});rn" ; echo "</script>rn" ; } } else { echo $page_cache ; // แสดงข้อมูลที่ทำการ cache echo "Cache Data" ; // สำหรับทดสอบว่า เป็นข้อมูลที่ได้จากการ cache หรือไม่ เมื่อใช้งาน สามารถ comment บรรทัดนี้ หรือลบทิ้งได้ } ?> |
โค้ดไฟล์ genCache.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php include ( "cache-kit.php" ); // เรียกใช้ไฟล์ php class $cache_active = true; // กำหนดให้ทำการ cache $cache_folder = 'cache/' ; // กำหนดไฟลเดอร์ที่ไว้เก็บไฟล์ cache $url = $_POST [ 'nameFile' ]; $data = array ( 'genTime' => time()); $ch = curl_init( $url ); curl_setopt( $ch , CURLOPT_RETURNTRANSFER, true); curl_setopt( $ch , CURLOPT_POST, 1); curl_setopt( $ch , CURLOPT_POSTFIELDS, $data ); $data = curl_exec( $ch ); curl_close( $ch ); acmeCache::save( $_POST [ 'nameFile' ]. $n_browser , $data ); // ทำการบันทึก html จากตัวแปร $page_cache ไว้ใน cache ชื่อ page_cache ?> |
ลิ้งค์ตัวอย่าง
#