Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - php tags in .js file

How do I enter a <? echo "hello"; ?> in a .js file. This is a jquery app, therefore the js file.

Thanks Jean

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would only be able to do this if the PHP interpreter is configured to run on *.js files, which by default it won't be. Quite honestly, I wouldn't recommend this behavior.

What I'd do instead is something like this (This method can be used for CSS files, too.):

<script type="text/javascript" src="js.php"></script>

js.php

<?php
//GZIP the file and set the JavaScript header
ob_start("ob_gzhandler");
header("Content-type: text/javascript");

//Set a JavaScript variable based on PHP work
echo 'var logged_in_user = "'.$_SESSION['username'].'";';

//Require an external script
require_once($_SERVER['DOCUMENT_ROOT']."/path/to/jquery.js");
?>

//More Javascript functions and code here
$(document).ready(function() {
  $('#mydiv').tipsy();
});

<?php
//Flush the output buffer
ob_end_flush();
?>

I personally do this for many reason.

  1. I have many jQuery files I want to include, but I don't want my browser doing 5+ HTTP requests. Including them all in one file means less HTTP requests.

  2. GZIP! I'm significantly reducing the size of the file be transferred and that speeds things up for the visitor.

  3. It's a central location to add, remove, or modify my JavaScript for the whole site. I can even use $_GET checks to make certain scripts conditional based on how I wrote the <script> tag.

    For example, <script type="text/javascript" src="js.php?var=1"></script>. I can then check $_GET['var'] within the js.php file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...