How to internationalize the string used in javascript code?

When developing an AJAX program, I came across a design solution for creating an I18N string in JavaScript.code. Some string is used only by JavaScript. For example.

$('#submit').click(function() {
    $(#target).html('Please wait while submitting...').load(someURI);
}

I would like the I18N line "Wait while you send ...". I am not sure if this is the best way to do this. Currently, I have an I18N-ed line on the server and is displayed in the javascript variable on the page (I am using PHP / wordpress).

<script>strSubmit = <?php  _e('Please wait while submitting...'); ?></script>

Then in javascript I just use varialble

$('#submit').click(function() {
    $(#target).html(strSubmit).load(someURI);
}

It works, but it looks messy. Is there a better way to achieve this?

+5
source share
4 answers

, php- javascript

<script src="script.php?file=blah.js">

script.php - -

    function _repl($x) { return '"' . _e($x[1]) . '"'; }

    $js = file_get_contents($_GET['file']);
    $js = preg_replace_callback('~_e\("(.+?)"\)~', '_repl', $js);
    echo $js;

_e(something) javascript-

+2

JSON l10n JSON:

// In the <head> tag :
<script type="text/javascript" src="locales.php"></script> 

locales.php:

var l10n = <?php echo json_encode($l10n); ?>;

$l10n - , , :

$l10n = array(
  'Please wait while submitting...' => 'Veuillez patienter durant le traitement...',
  'bah' => 'bih'
);

JS:

function $T(s){
  return l10n[s] || s;
}

alert($T('Please wait while submitting...'));
+10

You can generate text in the source script.

$('#submit').click(function() {
    $(#target).html('<?php  _e('Please wait while submitting...'); ?>').load(someURI);
}
0
source

you can create a kind of REST application in which you must fill in javascript line elements when loading a document from a service:

$(function(){
   var handleResponse = function.....; // fill your string elements from response
   var lang = "fr"; // language of localized document

   $.ajax(
       type: "GET",
       url: "/i18n.php?lang=" + lang + "&names=someName+someName1+someName2",
       success: handleResponse
   ); 
});
0
source

All Articles