[心得] 外部呼叫JavaScript跟PHP

看板PHP作者時間19年前 (2007/02/21 01:31), 編輯推噓3(301)
留言4則, 4人參與, 最新討論串1/1
HTML版本 http://blog.pixnet.net/kewang/post/2848937 看到一堆人在blog上面做線上人數的偵測,我就想說,為什麼一定要依賴別人的網站來 產生這個功能呢?然後就自己查了一下相關的資料。 因為一般blog的自訂欄位只能擺javascript的語法,可是像這種線上人數偵測的功能,通 常都是要搭配PHP才能做的出來。還有部落格觀察也是一樣使用js加上php,看了一下部落 格觀察的js code,又上google查了一些資料,終於知道怎麼實作出來了。 一開始我們有兩個檔案foo.js還有ip.php,內容分別為 foo.js document.write("hello world"); document.write("the editor is kewang"); 執行結果為 hello world the editor is kewang ip.php <?php $serverIP=$_SERVER['REMOTE_ADDR']; echo "the IP is $serverIP"; ?> 執行結果為 the IP is xxx.xxx.xxx.xxx 我們知道,一般在呼叫外部JavaScript的方式都是像下面這種方法 <script type="text/javascript" language="JavaScript" src="foo.js"></script> 如果現在要顯示的結果為下面這種功能,就要把PHP和JavaScript結合在一起 hello world the editor is kewang the IP is xxx.xxx.xxx.xxx 可是我們現在要執行php的話,那該怎麼寫?簡單,就改成下面這種形式 <script type="text/javascript" language="JavaScript" src="ip.php"></script> 然後將ip.php的內容改成下面這種 <?php Header("content-type: application/x-javascript"); $serverIP=$_SERVER['REMOTE_ADDR']; echo "document.write(\"hello world\");"; echo "document.write(\"the editor is kewang\");"; echo "document.write(\"the IP is" . $serverIP . "\");"; ?> Header那一行主要是要跟browser說,ip.php這個檔案解譯出來的檔案是javascript檔, 既然如此,那下面的輸出指令當然也是要遵守javascript的語法了, 所以我們將document.write包在echo的裡面。 除了輸出指令以外,其他部分可以利用PHP的語法撰寫程式, 這樣子我們就可以一邊利用PHP的$_SERVER取出IP,一邊用javascript顯示資料, 大功告成!只要這篇文章了解之後,顯示線上人數的功能也不難完成了。 參考資料: External JavaScript and PHP -- 雜七雜八的kewang部落格 http://kewang.pixnet.net -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.139.56.187

02/21 08:14, , 1F
好用
02/21 08:14, 1F

02/21 09:57, , 2F
Good!
02/21 09:57, 2F

02/21 10:17, , 3F
Good
02/21 10:17, 3F

02/21 17:01, , 4F
推!簡單易懂
02/21 17:01, 4F
文章代碼(AID): #15sp1YhQ (PHP)
文章代碼(AID): #15sp1YhQ (PHP)