Ajax, JSON, prototype and the encoding
I am using the prototype library for Ajax in my application for nearly two years now. First I transfered XML date between the server and the client as response but then I switched to using JSON. Using JSON is much faster, less data has to be transfered and avoids multiple browser problems with parsing XML (e.g. this one).
Changing my code to communicate using JSON was very simple. I just created a string containing my JSON code using JSON-lib an put it into the X-JSON http header field. This field is automatically parsed by prototype 1.5.1 and handed over to the onSuccess function as the second paramater:
onSuccess: function(transport, json) {
... do something with my json object
}
Everything worked fine until I tried to transfer characters that are not simple ASCII characters (e.g. äöü). These characters were not correctly displayed when dynamically loaded and placed into my page. I was using UTF-8 throughout my entire application (see an earlier post why) and the AJAX response was sent with charset UTF-8 too. So what is the problem?
After doing some research I found out that the there is no standard that allows to set the encoding of HTTP header fields. There is already a discussion going on inside the prototype development team about how to handle this.
I found this mail that suggests a workaround for current prototype versions. I changed my onSuccess method to the following:
onSuccess: function(transport) {
json = transport.responseText.evalJSON();
obj.options.handler(transport, json);
}
This evaluates the response body for JSON notation. On the server side I am simply writing the JSON string into the response body instead of the X-JSON header field.




