I have a use case where I make a cross domain JSONP request.
$.ajax({
url: "http://anyorigin.com/get/?url=<any_website_url>&callback=?'",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}});
It was working fine but I noticed that for Chinese websites data comes garbled. I debugged this and found out that response-header is always set to:
Response Header: Content-Type:text/javascript; charset=ISO-8859-1
Now this charset ISO-8859-1 is creating a problem. It should have been UTF-8. I basically want to always override this charset to UTF-8. I know I can do this using ajax. I tried using the following code -
$.ajax({
url: "http://anyorigin.com/get/?url=www.google.com&callback=?'",
dataType: 'jsonp',
beforeSend: function(xhr) {
console.log(xhr);
xhr.overrideMimeType("text/javascript; charset=utf-8");
},
success: function(data) {
console.log(data);
}});
But this did not fix the problem. I am guessing as JSONP request does not use XHR object, this will not work.
Can anyone tell me how I can achieve this or if it is even achievable? TIA.
You are correct that JSONP does not use the XHR object, it uses a script
tag.
However, this can be done through the jQuery JSONP wrapper using the scriptCharset
option.
scriptCharset
Type: String
Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the
charset
attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script.
All you have to do to get jQuery to add the UTF-8
charset
attribute to the JSONP script
tag is add scriptCharset: 'UTF-8'
to your AJAX settings object.
$.ajax({
url: "http://anyorigin.com/get/?url=<any_website_url>&callback=?'",
dataType: 'jsonp',
scriptCharset: 'UTF-8',
success: function(data) {
console.log(data);
}});