问题
Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)
I have several constants in a PHP application I'm developing. I've defined a Constants class and the defined the constants as const VAR_NAME = value; in this class. I would like to share these constants between my JavaScript and PHP code. Is there a DRY (Don't Repeat Yourself) mechanism to share them?
class Constants {
const RESOURCE_TYPE_REGSITER = 2;
const RESOURCE_TYPE_INFO = 1;
}
回答1:
I would use json_encode
. You will have to convert the class to an associative array first.
$constants = array("RESOURCE_TYPE_REGISTER"=>2, "RESOURCE_TYPE_INFO"=>2);
echo json_encode($constants);
You could also use reflection to convert the class to an associative array if you would prefer to use a class.
function get_class_consts($class_name)
{
$c = new ReflectionClass($class_name);
return ($c->getConstants());
}
class Constants {
const RESOURCE_TYPE_REGSITER = 2;
const RESOURCE_TYPE_INFO = 1;
}
echo json_encode(get_class_consts("Constants"));
回答2:
Put a list of constants common to both JavaScript and PHP in "client_server_shared.js".
'var' is required in JavaScript, and is legal (though deprecated) in PHP if inside a class. '$' to start a variable name is required in PHP, and legal in JavaScript.
var $shared_CONSTANT1 = 100;
var $shared_CONSTANT2 = 'hey';
PHP Code:
eval('class Client_server_shared{' ."\n"
. file_get_contents( 'client_server_shared.js' ) ."\n"
. '}'
. '$client_server = new Client_server_shared();'
);
echo $client_server->shared_CONSTANT1; // Proof it works in PHP.
echo $client_server->shared_CONSTANT2;
JavaScript Code:
alert( $shared_CONSTANT1 ); // Proof it works in JavaScript.
alert( $shared_CONSTANT2 );
回答3:
The only way you can share the constants is to have the php side inform the javascript. For instance:
echo "<script> var CONSTANT1 =".$constant_instance->CONSTANT_NAME.";</script>";
Or using ajax, you could also write a small script that would return the constants as JSON/whatever.
回答4:
A bit of an ugly hack, but here it goes:
constants.js
//<?php $const1 = 42; $const2 = "Hello"; //?>
constants.html (use inside JavaScript)
<script type="text/javascript" src="constants.js"></script>
<script type="text/javascript">document.write($const1);</script>
constants.php (use inside PHP)
<?php
ob_start(); // start buffering the "//"
require "constants.js";
ob_end_clean(); // discard the buffered "//"
echo $const1;
?>
来源:https://stackoverflow.com/questions/440494/share-constants-between-php-and-javascript