views:

15831

answers:

2

In my web app, i submit some form fields with JQuery $.getJSON() Method. I am having some problems with the encoding. The character-set of my app is charset=ISO-8859-1 but i think this fields are submitted with UTF-8.

Does anyone know, how can i set encoding in $.getJSON calls?

+4  A: 

I think that you'll probably have to use $.ajax() if you want to change the encoding, see the contentType param below (the success and error callbacks assume you have <div id="success"></div> and <div id="error"></div> in the html):

$.ajax({
    type: "POST",
    url: "SomePage.aspx/GetSomeObjects",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $("#error").html(XMLHttpRequest.responseText);
    }
});

I actually just had to do this about an hour ago, what a coincidence!

travis
+12  A: 

If you want to use $.getJSON() you can add the following before the call :

$.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});

You can use the charset you want instead of utf-8.

The options are explained here.

contentType : When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.

scriptCharset : Only for requests with 'jsonp' or 'script' dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.

You may need one or both ...

Pat
hi Pat, I'm having same problem of setting content type with getJSON method. I used $.ajaxSetup just before calling getJSON, but no change occurs, the "nordic" characters becomes junk characters in my DB. could you pls tell me the exact order of calling mathods? thnx
Bhupi