Wednesday, April 15, 2009

How I Solved my Python, Django & jQuery Javascript Unicode Problems

JavaScript:

The JavaScript encode() function doesn't handle Unicode. See http://xkr.us/articles/javascript/encode-compare/ for alternatives.

The jQuery serialize() function works well with Unicode.

Python:

urllib.urlencode(), urllib.quote() and urllib.quote_plus don't handle unicode strings. So instead of

urllib.urlencode(u'a unicode string')

... do:

urllib.urlencode(u'a unicode string'.encode('utf-8'))

In the above case I'm assumming that the string is already Unicode (which seems to be the case when you got it off Django, maybe from a GET parameter). If it's in another encoding, you must previously do:

'a byte string encoded in X'.decode(encoding_goes_here).encode('utf-8')

No comments:

Post a Comment