views:

266

answers:

2

Hello,

I'm running into a character encoding issue when I load a dropdown using jQuery from an external js file. This only seems to happen when the JavaScript object is not within the page.

For example the below is the JavaScript object.

var langs = [
  {value:'zh-CN', text:'中文 (简体) Chinese Simplified'},
  {value:'en', text:'English'},
  {value:'eo', text:'EsperAnt'},
  {value:'es', text:'Español'},
  {value:'ja', text:'日本語 (Japanese)'},
  {value:'pt-PT', text:'Português'},
  {value:'ru', text:'Русский (Russian)'},
 ];

If this is in my page with the proper meta tags <meta http-equiv="content-type" content="text/html; charset=utf-8" /> the below code works.

$(document).ready(function() {
                // Fill language select
                $.each(langs, function(i, j){  
     $('#LangSelect').append($("<option></option>").attr("value",j.value).text(j.text));
                });

But, since I need languages on more then one page I've moved the langs object to an external js file and reference it. After doing this, I run into encoding issues such as russian characters become Русский (Russian).

This encoding issues seems to still appear even when the reference to the external js file is set as below:

<script type="text/javascript" charset="UTF-8" src="externalJS.js"></script>

Is there anyway to force the JavaScript object to be loaded with the proper encoding from an external file?

Please note I am experiencing these issues when viewing content on the iPhone Mobile Safari browser. Additionally these pages are simply html and JavaScript without any server side components.

Thanks in advance, Ben

A: 

Make sure you save the javascript file using UTF-8 encoding. If you open the file in Notepad++, then you can click Format>Encode in UTF-8 (If you try Format>Convert to UTF-8, then have a look at the page using a hex editor. Sometimes you end up with some strange characters at the beginning of the file).

Marius
Thanks Marius. Have tried that with no luck.
Ben Bahrenburg
A: 

Is there anyway to force the JavaScript object to be loaded with the proper encoding from an external file?

Yes, the script charset attribute as you quoted. However it historically didn't work everywhere and was best not relied on. Where this is not supported, the browser will always use the charset of the main page as the charset in the script. So as long as you include the UTF-8 charset parameter in the main page you should be fine either way.

I am surprised if a modern browser like Mobile Safari doesn't understand it, though.

Is it possible your server might be serving .js files with a bad Content-Type header containing a wrong charset? A combination of unset mime-types for JS plus AddDefaultCharset in Apache could leave you with:

Content-Type: text/plain;charset=iso-8859-1

Which might maybe have the effect of mucking it up.

bobince