dongou6632 2013-03-29 12:21
浏览 35
已采纳

如何在javascript文件中插入php变量?

My page is available in 3 languages and I'm including in the header of each file (index, contact, etc.) the selected language file (en, ru, pl).

<?php
session_start();
include('language/'.$_SESSION['lang'].'.php');
?>

en.php

<?php
session_start();
$lang = array();

$lang['hello'] = 'Hello';
$lang['world'] = 'World !';
?>

ru.php

<?php
session_start();
$lang = array();

$lang['hello'] = 'привет';
$lang['world'] = 'мир';
?>

And this is how I'm echoing them:

<p><? echo $lang['hello'].' '.$lang['world'];?></p>

This is working actually fine, but I'm having problem with my .js files. If I want to alert or insert some text somewhere I can't.

For example in one of my .js file I have an alert:

if (something_obj.val() == ''){
   alert('Wrong username given !');
   return false;
}

How can I implement language files in my js files? Am I need to create a news .js language file?

  • 写回答

2条回答 默认 最新

  • dongshendie8849 2013-03-29 12:27
    关注

    You could have one js file per language with translations looking like this:

    // german.js
    var translations = {
      'hello': 'hallo',
      'world': 'welt'
    };
    

    In other JS scripts, just do something like this:

    alert(translations['hello'] + " " + translations['world'])
    

    Of course, you might want to choose a shorter variable name than translations.

    Then, in your php file, include the correct JS script based on the language:

    <script src="languages/<?php echo $_SESSION['lang']; ?>.js"></script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程