javascript 编码地狱!JSON ajax请求(utf-8)到Latin1大写字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8079216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Encoding hell! JSON ajax request (utf-8) to Latin1 uppercase characters
提问by Jo?o Pereira
I've ran into the following problem: the javascript lib i'm working on uses JSON cross-domain requests to get data from a Ruby on Rails backend:
我遇到了以下问题:我正在处理的 javascript 库使用 JSON 跨域请求从 Ruby on Rails 后端获取数据:
function getData()
{
$.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")} })
$.ajax({
url: backend_server + '?callback=parseData&op=516',
contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
success: function (xml) {
//console.log('success');
}
});
}
The database from which RoR gets the data uses latin1internally but, if memory serves correct, this kind of JSON requests can only be done using UTF-8.
RoR 从中获取数据的数据库在内部使用latin1,但如果内存正确,这种 JSON 请求只能使用 UTF-8 完成。
The webpage's header reads:
网页的标题如下:
Content-Type text/html; charset=ISO-8859-1
And the page's metatag is also ISO-8859-1:
页面的元标记也是 ISO-8859-1:
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
Now, after getting the data from the request, my Javascript library would parse it and, eventually, append it to a certain div inside the page (using the latest JQuery, not that it matters). All the latin characters were displayed incorrectly.
现在,从请求中获取数据后,我的 Javascript 库将解析它,并最终将其附加到页面内的某个 div(使用最新的 JQuery,这并不重要)。所有拉丁字符都显示不正确。
I noticed that different browsersinterpreted these characters differently (for some it worked fine, for others... not so much). I ended making a slight change to a utf8_decode function i found here(detecting the user agent and skipping the processing entirely for Safari, IE and Opera) but in the end I still can't display special Latin Uppercase characters with such as "é", "?", "à", "á", "?" or "?".
我注意到不同的浏览器对这些字符的解释不同(对于一些它工作得很好,对于其他人......不是那么多)。我结束了对我在此处找到的 utf8_decode 函数的轻微更改(检测用户代理并完全跳过 Safari、IE 和 Opera 的处理)但最后我仍然无法显示特殊的拉丁大写字符,例如“é” , "?", "à", "á", "?" 或者 ”?”。
Any ideas? I am rather lost and could use some tips. Thanks in advance, J.
有任何想法吗?我很迷茫,可以使用一些技巧。提前致谢,J。
PS: the top comment on the function's website is mine too.
PS:功能网站上的最高评论也是我的。
Edit1: I've also tried using unescape(encodeURIComponent(str_data))
but it didn't work either
Edit1:我也试过使用,unescape(encodeURIComponent(str_data))
但也没有用
回答by Gerben
If the page is latin, and the server uses latin, why would you want you json to be utf-8. JSON doesn't have to be utf-8!
如果页面是拉丁语,而服务器使用拉丁语,为什么要让 json 为 utf-8。JSON 不必是 utf-8!
Try removing the utf-8 from the contentType parameter in your code above.
尝试从上面代码中的 contentType 参数中删除 utf-8。