简体   繁体   中英

Is it possible to post values to external javascript file?

Hay,

I was wondering if it's possible to execute php code in external javascript file? For example i need to read user language and such.

You can run PHP in a js file if you add the PHP handler to text/javscript .

<Files *.js>
AddType application/x-httpd-php .js
</Files> 

Be sure to have your JavaScript file identify itself with...

 header('Content-Type: text/javascript');

But...

As you can imagine, every JavaScript file running through PHP isn't a good idea.

So what I would and do use, is this...

<script type="text/javascript">
var lang = '<?php echo $lang; ?>';

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

Then inside of common.js , you can access lang variable.

You can run PHP to generate a JavaScript file, which the user's browser would then run.

But PHP runs on the server-side. There's no way to send PHP to a user to run.

It's not clear exactly what you want from your question...

But you can execute PHP/server-side languages via AJAX . If you are not already I would recommend using a javascript framework . (i prefer jQuery myself).

Here is a basic example of an AJAX call using jQuery.

PHP

//yourscript.php
echo "ajax is awesome!";

JavaScript

$.ajax({
  url: 'yourScript.php',
  success: function(response){
    //alerts "ajax is awesome!"
    alert(response);
  }
});

If you check out some of the documentation on the jQuery ajax method it should give you a good idea of what ajax is used for. It essentially works backwards from how your question is phrased . An ajax call is initiated on the server side, and the php script responds. So in essence it accomplishes the same goal.

The real trick is how you are going to format your data. I use XML but it seems that JSON is a bit more popular (not a fact at all... just my impression). But either way you are able to pass complex sets of data that greatly ease the data parsing process.

You can call:

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

and execute PHP in that file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM