Friday, 14 February 2014

Get JSON with JQuery as UTF-8

This is how I used JQuery, to read JSON from a url:

$.getJSON('data-html5.json').then( 
    function(data){  
        console.log(data);
        nextChart(data, 'canvas', 'tip');
    },
    function(jqXHR, textStatus, errorThrown) {
        alert("Error: " + textStatus + " errorThrown: " + errorThrown);
    } 
);

But this method does not interpret UTF-8 characters, making your UTF-8 text to look scrambled. The workaround is to use the following:

$.ajax({
    type: "POST",
    url: "data-html5.json",
    contentType: "application/json; charset=utf-8",
    dataType: "json",    
    success: function(data) {
        console.log(data);
        nextChart(data, 'canvas', 'tip');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert("Error: " + textStatus + " errorThrown: " + errorThrown);
    }
});  

No comments:

Post a Comment