Javascript Jquery 忽略编码 ISO-8859-1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8988573/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:18:25  来源:igfitidea点击:

Jquery ignores encoding ISO-8859-1

javascriptjquerycharacter-encodingcontent-typeiso-8859-1

提问by Spike2050

I have a website which apperently removes the correct encoding (ISO-8859-1) from a string and sends it wrong.

我有一个网站,它显然从字符串中删除了正确的编码 (ISO-8859-1) 并将其发送错误。

I have this encoding specified in my HTML

我在我的 HTML 中指定了这种编码

<meta charset="ISO-8859-1">

I load my javascript via

我通过加载我的javascript

<script type="text/javascript" charset="ISO-8859-1" src="...

I send for Information via JQuery Ajax Request like this (with german special character '?' and '?'):

我通过这样的 JQuery Ajax 请求发送信息(带有德语特殊字符“?”和“?”):

$.ajax({
    url: '..',
    type: 'POST',
    contentType: 'application/xml;charset=ISO-8859-1',
    data: xmlRequest.html(),...

This is translated into a request and in the chrome developer tools I see this in the Request Header:

这被转换为请求,在 chrome 开发人员工具中,我在请求标头中看到了这一点:

..
Content-Type: application/xml;charset=UTF-8
..

What happened there?

那里发生什么了?

Of course the special characters are encoded wrong ("??" instead of "?") the server can't understand me and i get an error.

当然,特殊字符编码错误(“??”而不是“?”)服务器无法理解我,我收到错误消息。

回答by iappwebdev

Because I had the same problem, I'll provide a solution that worked for me. Background: Microsoft Excel is too stupid to export a CSV-File in charset UTF-8:

因为我遇到了同样的问题,所以我会提供一个对我有用的解决方案。背景:Microsoft Excel 太笨了,无法以 UTF-8 字符集导出 CSV 文件:

$.ajax({
    url: '...',
    contentType: 'Content-type: text/plain; charset=iso-8859-1',
    // This is the imporant part!!!
    beforeSend: function(jqXHR) {
        jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
    }
});

回答by JMM

According to the jQuery.ajax()contentTypedocumentation:

根据jQuery.ajax()contentType文档

Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side."

数据将始终使用 UTF-8 字符集传输到服务器;您必须在服务器端对此进行适当的解码。”