PHP動態產生javascript檔案的2個例子

來源:互聯網
上載者:User

 這篇文章主要介紹了PHP動態產生javascript檔案的2個例子,需要的朋友可以參考下

一、PHP動態產生 第一步:在PHP檔案中直接寫入JS代碼,並在頭部聲明這是一個JavaScript檔案  代碼如下:<?php header('Content-Type: application/x-javascript; charset=UTF-8');?>第二步:用PHP輸出轉義JavaScript代碼 代碼如下:function jsformat($str){    $str = trim($str);    $str = str_replace('ss', 's', $str);    $str = str_replace(chr(10), '', $str);    $str = str_replace(chr(13), '', $str);    $str = str_replace('    ', '', $str);    $str = str_replace('', '', $str);    $str = str_replace('"', '"', $str);    $str = str_replace(''', ''', $str);    $str = str_replace("'", "'", $str);    return $str;}直接調用jsformat($str)最後一步:進行url重寫,比如PHP地址為 xxx/123.php 只要重寫成 xxx/123.js 至此已經達成目的。 以PHPCMS為例 代碼如下:<?php header('Content-Type: application/x-javascript; charset=UTF-8');?>{pc:content action="position" posid="1" order="id DESC" num="7" $catid=11}<?phpfunction jsformat($str){    $str = trim($str);    $str = str_replace('ss', 's', $str);    $str = str_replace(chr(10), '', $str);    $str = str_replace(chr(13), '', $str);    $str = str_replace('    ', '', $str);    $str = str_replace('', '', $str);    $str = str_replace('"', '"', $str);    $str = str_replace(''', ''', $str);    $str = str_replace("'", "'", $str);    return $str;}?>{loop $data $v}document.writeln("<?php echo jsformat("<a href="$v[url]"><img src="$v[thumb]"></a>");?>");{/loop}{/pc}每一個迴圈都用 document.writeln()寫出轉移後的代碼。 二、PHP include JS檔案 通過html寫javascript引入一個php的連結,該php實際上是產生js的檔案:  代碼如下:if (20 == $ad_type_id) { // 對聯 ob_start (); include TMPL_PATH . 'Code/duilian.js'; header("content-type: application/x-javascript"); $code = ob_get_clean (); echo $code;} 在php裡面include js檔案,js裡面的var swf這樣的變數,var swf = ‘‘,這裡使用ob緩衝,注意加上header(“content-type: application/x-javascript”),讓瀏覽器知道這是個javascript的指令檔。 頁面上這樣引用:  代碼如下:<script src="http://tg.1155t.cn/code/53/" language="JavaScript"></script> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.