This article mainly introduces two examples of PHP dynamic javascript file generation. For more information, see
This article mainly introduces two examples of PHP dynamic javascript file generation. For more information, see
I. Dynamic PHP generation
Step 1: directly write JS code in the PHP file, and declare in the header that this is a JavaScript file
The Code is as follows:
Step 2: Use PHP to output escape JavaScript code
The Code is as follows:
Function jsformat ($ str)
{
$ Str = trim ($ str );
$ Str = str_replace ('\ s \ s',' \ 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;
}
Directly call jsformat ($ str)
Last step: rewrite the url. For example, if the PHP address is xxx/123.php, rewrite it to xxx/123.js.
Taking PHPCMS as an Example
The Code is as follows:
{Pc: content action = "position" posid = "1" order = "id DESC" num = "7" $ catid = 11}
Function jsformat ($ str ){
$ Str = trim ($ str );
$ Str = str_replace ('\ s \ s',' \ 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 (" ");
{/Loop}
{/Pc}
Every loop uses document. writeln () to write the code after transfer.
Ii. PHP include JS files
Use html to write javascript to introduce a php link. This php actually generates a js file:
The Code is as follows:
If (20 = $ ad_type_id) {// Couplet
Ob_start ();
Include TMPL_PATH. 'Code/duilian. js ';
Header ("content-type: application/x-javascript ");
$ Code = ob_get_clean ();
Echo $ code;
}
Include the js file in php and the var swf variable in js. var swf = ''. ob cache is used here. Note that the header (" content-type: application/x-javascript) to let the browser know that this is a javascript script file.
Reference on the page as follows:
The Code is as follows: