gpt4 book ai didi

javascript - 在php中动态生成javascript还是为多语言界面执行ajax?

转载 作者:行者123 更新时间:2023-11-28 01:32:58 25 4
gpt4 key购买 nike

我必须用几种不同的外语实现一个 webapp 界面。我发现我正在编写的 jquery 函数取决于正在实现的语言。例如:

    <?php 
require 'nl.php';
/*
if(isset($_SESSION['lang'])){
$lang = $_SESSION['lang'];
if(!empty($lang)){
if($lang == 'en'){
require 'en.php';
}else if($lang = 'nl'){
require 'nl.php';
}
}
}
*/


?>

<html>
<head>
</head>
<body>
<textarea id = "notes"><?php echo $string_lib['ENTER_NOTES'];?></textarea>

<script type="text/javascript" src= "js/jquery.js"></script>
<script type="text/javascript" src= "js/clicknotes.js"></script>
</body>
</html>

因此这需要一个提供数组的语言文件。注释掉的部分只是为了演示我如何确定要发送的语言。第一个 require 命令在其位置上起作用。现在这是语言文件。

nl.php:

<?php 
$string_lib = array(
'ENTER_NOTES' => 'Vul hier uw notities.',
'ENTER_PASSWORD' => 'Vul hier uw wachtwoord in.',
);

和en.php

<?php 
$string_lib = array(
'ENTER_NOTES' => 'Enter your notes here.',
'ENTER_PASSWORD' => 'Enter your password here.',
);


?>

现在,当我开始在 javascript 中执行某些操作时就会出现问题,例如,clicknotes.js:

$(window).load(function(){
$(document).ready(function(){
$('#notes').focusin(function(){
if($(this).text() == 'Enter your notes here.'){
$(this).text('');
}
//alert($(this).text());
});
});
});

所以我要么必须使用与 html 相同的方法用 php 动态生成 javascript,如下所示:

<?php 
header('Content-type: text/javascript');
?>

$(window).load(function(){
$(document).ready(function(){
$('#notes').focusin(function(){
if($(this).text() == '<?php echo $string_lib['ENTER_NOTES'];?>'){
$(this).text('');
}
//alert($(this).text());
});
});
});

或者我必须在 javascript 中发送等效数组并在 javascript 中调用这些变量,即if($(this)).text() == string_lib['nl']['ENTER_NOTES'])。或者我想我可以执行 ajax 请求来获取我需要的数组。

那么,您认为以下哪种方法最有利于可维护性和易于修改?

最佳答案

您还可以加载额外的 JavaScript(通过 <script> 或 RequireJS)或 JSON(通过 AJAX)文件,例如 text_en.jstext_fr.json这将定义翻译的哈希值;那么你可以简单地使用TEXT.enter_your_notes_here或 JS 代码中的类似内容。这与您的PHP解决方案类似,但不涉及动态生成JS。

专业版:

  • 您的 JS 代码保持干净
  • 所有文本都可以轻松翻译,因为它们都集中在一处
  • gettext 非常相似其他语言使用的国际化方法

缺点:

  • 对翻译文件的额外要求

关于javascript - 在php中动态生成javascript还是为多语言界面执行ajax?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com