开发者

Is it possible to post values to external javascript file?

开发者 https://www.devze.com 2023-01-28 11:57 出处:网络
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 PH

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.


You can call:

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

and execute PHP in that file.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消