PHP 和 JavaScript 的通用常量文件

发布于 2024-08-31 12:09:34 字数 93 浏览 6 评论 0原文

为了不重复代码,大家建议如何在 PHP 和 JavaScript 之间共享常量文件? XML 文件?我假设在 PHP 中混合 javascipt 不是正确的解决方案!?谢谢

How do guys suggest to share a constants file between PHP and JavaScript, in order not to repeat code? XML file? I am assuming mixing up javascipt inside PHP would not be the right solution!? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

或十年 2024-09-07 12:09:34

http://php.net/manual/en/book.json.php

我会说使用 json。它是 javascript 原生的,并且有一个 php 解析器库。

考虑以下内容:

json:

{constants : { var1 : "value 1", var2 : "value 2", var3 : "value 3"}}

然后将其读入 php:

$const = json_decode(json_string);

这将为您提供对象 $const ,其属性类似于 $const->{'var1'} 返回“值 1”。

在 JavaScript 中,这将是:

var const = eval(json_string);

并且会给你 const.constants.var1 == "value 1"。

js 最简单的实际实现是:

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

当添加 html 输出时,您立即拥有一个常量对象,并将其他对象作为其子对象。

http://php.net/manual/en/book.json.php

I would say use json. It is native to the javascript and there is a parser library for the php.

consider the following:

json:

{constants : { var1 : "value 1", var2 : "value 2", var3 : "value 3"}}

and then read it into php:

$const = json_decode(json_string);

This gives you the object $const with properties like $const->{'var1'} returning "value 1".

in JavaScript this would be:

var const = eval(json_string);

and would give you const.constants.var1 == "value 1".

Easiest implementation in real terms for js is:

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

When added the html output you instantly have a constants object with the other objects as its children.

束缚m 2024-09-07 12:09:34

你可以试试我的方法。我创建了一个与 php 和 js 文件一起使用的通用配置文件。

看看这个技巧:

PHP 类配置文件:

<?php
/** Class Start **/
class Config {    
    /********************************/
    /* Page Config Info */
    /********************************/
    // page title
    const PAGE_TITLE = 'Welcome in Code Era!';  
    // base url 
    const BASE_URL = 'http://www.myapp.com/';  
    /********************************/
    /* Database Config Info */
    /********************************/
    // mysql host server
    const SERVER = '10.102.23.141';
    // database user name
    const USER = 'root';
    // database password
    const PASSWORD = '';
    // mysql database name
    const DATABASE = 'sample';
    /********************************/
    /* Share Message */
    /********************************/
    // Facebook Share Message
    const FB_SHARE_MESSAGE = 'This gonna my share message'; 
    // Facebook Share Title 
    const FB_SHARE_TITLE = 'This gonna my share title';      
    // Facebook Share Caption
    const FB_SHARE_CAPTION = 'This gonna my share caption';      
}
/** Class End **/
?>

JavaScript 文件:

// global config var
var config = {} || '' || null;
/**
 * Get Config data with Ajax Response Data
 * custom ajax method
 * return ajax response and use/store as javascript var
 * extend jQuery Ajax and change it
 * @param qs -> query string {q:value}
 * @returns result mix|multitype
 */
$.extend({
    getConfig : function (qs) {
        var result = null;
        $.ajax({
            url : 'GetConfig.php',
            type : 'POST',
            data : qs,
            dataType : "json",
            async : false,
            success : function (data) {
                result = data;
            },
            error : function ajaxError(jqXHR, exception) {
                if (jqXHR.status === 0) {
                    alert('Not connected.\nVerify your network.');
                } else if (jqXHR.status === 404) {
                    alert('The requested page not found. [404]');
                } else if (jqXHR.status === 500) {
                    alert('Internal Server Error [500].');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                    alert('Uncaught Error.\n' + jqXHR.responseText);
                }
            }
        });
        return result;
    }
});

// Collect all Class Constant data on page load
var CONFIG = (function() {
    var private = $.getConfig({config_item : ''});
    return {
       get: function(name) { return private.data[name]; }
   };
})();

/**
 * Facebook Share Content example code
 * with using class constant
 */
function fbShare() {
    var feed = {
        method : 'feed',        
        link : CONFIG.get('BASE_URL'),
        name : CONFIG.get('FB_SHARE_TITLE'),        
        caption : CONFIG.get('FB_SHARE_CAPTION')
    };
    function callback(response) {
        if (response && response.post_id !== undefined) {
            alert('Thank you for sharing the content.');
        }
    }
    FB.ui(feed, callback);
}

如何在 JavaScript 中使用:

var fbShareMessage = CONFIG.get('FB_SHARE_MESSAGE');

没有 CONFIG.get 函数示例:

var fbShareMessage = $.getConfig({config_item : 'FB_SHARE_MESSAGE'}).data;

GetConfig.php 文件的 PHP 代码:

<?php
/**
 *  Get Config php file
 *  request a config item from javascript/ajax
 *  return json data
 */
// check request with ajax only
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    exit;
}
// include class config
require_once '../class/class.config.php';
// get all constant from class config
$configConstant = new ReflectionClass('Config');
// store as array in var
$configConstantArray = ($configConstant->getConstants());
// safe and private request item
$black_list_constant = 'SERVER|USER|PASSWORD|DATABASE';
$black_list_object = explode('|',$black_list_constant);
// make return jason format
$result = array();
// get action from ajax
$action = $_POST['config_item'];
switch ($action) {
    case '':
    $result["status"]= TRUE;    
    foreach ($black_list_object as $index => $value){       
        if(array_key_exists($value, $configConstantArray)){
            unset($configConstantArray["$value"]);                  
        }       
    }
    $result["data"]= $configConstantArray;
    $result["msg"]= 'Response 200 OK';
    echo json_encode($result);
    break;
    default:
    // check valid action
    if(array_key_exists($action,$configConstantArray) && in_array($action,$black_list_object)){
        $result["status"]= FALSE;
        $result["data"]= null;
        $result["msg"]= 'Response 201 FAIL';
        echo json_encode($result);
    }else{
        $result["status"]= TRUE;
        $result["data"]= $configConstantArray["$action"];
        $result["msg"]= 'Response 200 OK';
        echo json_encode($result);
    }
    break;
}

就是这样。希望,它会对某人有所帮助:)

You can try my approach. I have created a common config file to use with php and js file.

Check out this trick:

PHP Class Config File:

<?php
/** Class Start **/
class Config {    
    /********************************/
    /* Page Config Info */
    /********************************/
    // page title
    const PAGE_TITLE = 'Welcome in Code Era!';  
    // base url 
    const BASE_URL = 'http://www.myapp.com/';  
    /********************************/
    /* Database Config Info */
    /********************************/
    // mysql host server
    const SERVER = '10.102.23.141';
    // database user name
    const USER = 'root';
    // database password
    const PASSWORD = '';
    // mysql database name
    const DATABASE = 'sample';
    /********************************/
    /* Share Message */
    /********************************/
    // Facebook Share Message
    const FB_SHARE_MESSAGE = 'This gonna my share message'; 
    // Facebook Share Title 
    const FB_SHARE_TITLE = 'This gonna my share title';      
    // Facebook Share Caption
    const FB_SHARE_CAPTION = 'This gonna my share caption';      
}
/** Class End **/
?>

JavaScript File:

// global config var
var config = {} || '' || null;
/**
 * Get Config data with Ajax Response Data
 * custom ajax method
 * return ajax response and use/store as javascript var
 * extend jQuery Ajax and change it
 * @param qs -> query string {q:value}
 * @returns result mix|multitype
 */
$.extend({
    getConfig : function (qs) {
        var result = null;
        $.ajax({
            url : 'GetConfig.php',
            type : 'POST',
            data : qs,
            dataType : "json",
            async : false,
            success : function (data) {
                result = data;
            },
            error : function ajaxError(jqXHR, exception) {
                if (jqXHR.status === 0) {
                    alert('Not connected.\nVerify your network.');
                } else if (jqXHR.status === 404) {
                    alert('The requested page not found. [404]');
                } else if (jqXHR.status === 500) {
                    alert('Internal Server Error [500].');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                    alert('Uncaught Error.\n' + jqXHR.responseText);
                }
            }
        });
        return result;
    }
});

// Collect all Class Constant data on page load
var CONFIG = (function() {
    var private = $.getConfig({config_item : ''});
    return {
       get: function(name) { return private.data[name]; }
   };
})();

/**
 * Facebook Share Content example code
 * with using class constant
 */
function fbShare() {
    var feed = {
        method : 'feed',        
        link : CONFIG.get('BASE_URL'),
        name : CONFIG.get('FB_SHARE_TITLE'),        
        caption : CONFIG.get('FB_SHARE_CAPTION')
    };
    function callback(response) {
        if (response && response.post_id !== undefined) {
            alert('Thank you for sharing the content.');
        }
    }
    FB.ui(feed, callback);
}

How to Use in JavaScript:

var fbShareMessage = CONFIG.get('FB_SHARE_MESSAGE');

Without CONFIG.get function example:

var fbShareMessage = $.getConfig({config_item : 'FB_SHARE_MESSAGE'}).data;

PHP Code for GetConfig.php File:

<?php
/**
 *  Get Config php file
 *  request a config item from javascript/ajax
 *  return json data
 */
// check request with ajax only
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    exit;
}
// include class config
require_once '../class/class.config.php';
// get all constant from class config
$configConstant = new ReflectionClass('Config');
// store as array in var
$configConstantArray = ($configConstant->getConstants());
// safe and private request item
$black_list_constant = 'SERVER|USER|PASSWORD|DATABASE';
$black_list_object = explode('|',$black_list_constant);
// make return jason format
$result = array();
// get action from ajax
$action = $_POST['config_item'];
switch ($action) {
    case '':
    $result["status"]= TRUE;    
    foreach ($black_list_object as $index => $value){       
        if(array_key_exists($value, $configConstantArray)){
            unset($configConstantArray["$value"]);                  
        }       
    }
    $result["data"]= $configConstantArray;
    $result["msg"]= 'Response 200 OK';
    echo json_encode($result);
    break;
    default:
    // check valid action
    if(array_key_exists($action,$configConstantArray) && in_array($action,$black_list_object)){
        $result["status"]= FALSE;
        $result["data"]= null;
        $result["msg"]= 'Response 201 FAIL';
        echo json_encode($result);
    }else{
        $result["status"]= TRUE;
        $result["data"]= $configConstantArray["$action"];
        $result["msg"]= 'Response 200 OK';
        echo json_encode($result);
    }
    break;
}

That's it. Hope, it will help to someone :)

醉生梦死 2024-09-07 12:09:34

PHP 和 JavaScript 共享的配置变量可以很容易地存储为 XML,是的。不过,JSON 可能是一个更好的解决方案,因为它需要最少的解析工作 - JS 在本机处理它,而 PHP 将其转换为带有 json_decode

Config variables to be shared by both PHP and JavaScript could easily be stored as XML, yes. JSON might be a better solution, though, as it requires minimal effort to parse - JS handles it natively, and PHP turns it into an array with json_decode.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文