java 另一个 JQuery 编码问题,在 IE 上

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

Another JQuery encoding problem, on IE

javajqueryajaxinternet-exploreriso-8859-1

提问by Marco Z

I'm coding an italian website where I need to validate some input data with an xhr call. My code for the ajax request's like this (I'm using JQuery 1.3.2):

我正在编写一个意大利网站,我需要在其中使用 xhr 调用验证一些输入数据。我的 ajax 请求代码是这样的(我使用的是 JQuery 1.3.2):

 $.ajaxSetup({
    type: "POST",
    timeout: 10000,
    contentType: "application/x-www-form-urlencoded; charset=iso-8859-1"        
}); 


 $.ajax({
    url: "ajaxvalidate.do",
    data: {field:controlInfo.field,value:controlInfo.fieldValue},
    dataType: "json",
    complete: function() {
        //
    },
    success: function(msg) {
        handleAsyncMsg(controlInfo, msg, closureOnError);
    },
    error: function(xhr, status, e) {            
        showException(controlInfo.id, status);

    }

});

On the backend I have a java struts action to handle the xhr. I need to use the encoding ISO-8859-1 in the page to ensure the data (specially accented characters) are sent correctly in the synchronous submit.

在后端,我有一个 java struts 操作来处理 xhr。我需要在页面中使用编码 ISO-8859-1 以确保在同步提交中正确发送数据(特别是重音字符)。

All's working like a charm in Firefox but when I have to handle an async post from IE 7 with accented characters I have a problem: I always receive invalid characters (utf-8 maybe?). EG I type in the form àààààààà and I get in my request this value: ? ? ? ? ? ? ? ?. Since the request charset's correctly set to ISO-8859-1 I can't understand why the server's still not parsing the form value correctly.

在 Firefox 中一切都像魅力一样工作,但是当我必须处理来自 IE 7 的带有重音字符的异步帖子时,我遇到了一个问题:我总是收到无效字符(也许是 utf-8?)。例如,我以 àààààààà 的形式输入,然后在我的请求中得到这个值:? ? ? ? ? ? ?. 由于请求字符集已正确设置为 ISO-8859-1,我无法理解为什么服务器仍未正确解析表单值。

This is a log sample with all the request headers and the error (the server's an old Bea Weblogic 8.1):

这是一个包含所有请求标头和错误的日志示例(服务器是旧的 Bea Weblogic 8.1):

Encoding: ISO-8859-1
Header: x-requested-with - Value: XMLHttpRequest
Header: Accept-Language - Value: it
Header: Referer - Value: https://10.172.14.36:7002/reg-docroot/conv/starttim.do
Header: Accept - Value: application/json, text/javascript
Header: Content-Type - Value: application/x-www-form-urlencoded; charset=iso-8859-1
Header: UA-CPU - Value: x86
Header: Accept-Encoding - Value: gzip, deflate
Header: User-Agent - Value: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Header: Host - Value: 10.172.14.36:7002
Header: Content-Length - Value: 65
Header: Connection - Value: Keep-Alive
Header: Cache-Control - Value: no-cache
Header: Cookie - Value: JSESSIONID=JQJlNpVC86yTZJbcpt54wzt82TnkYmWYC5VLL2snt5Z8GTsQ1pLQ!1967684811
Attribute: javax.net.ssl.cipher_suite - Value: SSL_RSA_WITH_RC4_128_MD5
Attribute: javax.servlet.request.key-size - Value: 128
Attribute: javax.servlet.request.cipher_suite - Value: TLS_RSA_WITH_RC4_128_MD5
Attribute: javax.servlet.request.key_size - Value: 128
Attribute: weblogic.servlet.network_channel.port - Value: 7001
Attribute: weblogic.servlet.network_channel.sslport - Value: 7002
Attribute: org.apache.struts.action.MESSAGE - Value: org.apache.struts.util.PropertyMessageResources@4a97dbd
Attribute: org.apache.struts.globals.ORIGINAL_URI_KEY - Value: /conv/ajaxvalidate.do
Attribute: errors - Value: org.apache.struts.util.PropertyMessageResources@4a97e4d
Attribute: org.apache.struts.action.MODULE - Value: org.apache.struts.config.impl.ModuleConfigImpl@4aa2ff8
Attribute: weblogic.servlet.request.sslsession - Value: javax.net.ssl.impl.SSLSessionImpl@42157c5
field: nome - value: ???????????????? - action: /endtim

采纳答案by bobince

contentType: "application/x-www-form-urlencoded; charset=iso-8859-1"

内容类型:“应用程序/x-www-form-urlencoded;字符集=iso-8859-1”

You can sayyou're sending a form submission as ISO-8859-1 in the header, but that doesn't mean you actually are. jQuery uses the standand JavaScript encodeURIComponent() method to encode Unicode strings into query-string bytes, and that alwaysuses UTF-8.

您可以您在标题中以 ISO-8859-1 格式发送表单提交,但这并不意味着您实际上是这样。jQuery 使用标准的 JavaScript encodeURIComponent() 方法将 Unicode 字符串编码为查询字符串字节,并且始终使用 UTF-8。

In any case, the ‘charset' parameter for the MIME type ‘application/x-www-form-urlencoded' is highly non-standard. As an ‘x-' type there is no official MIME registration for this type, but HTML 4.01 doesn't specify such a parameter and it would be very unusual for an ‘application/*' type. Weblogic claims to detect this construct, for what it's worth.

在任何情况下,MIME 类型“application/x-www-form-urlencoded”的“charset”参数都非常不标准。作为 'x-' 类型,该类型没有官方 MIME 注册,但 HTML 4.01 没有指定这样的参数,对于 'application/*' 类型来说这是非常不寻常的。Weblogic 声称能够检测到这种构造,这是值得的。

So what you can do is either:

所以你可以做的是:

1: create the POST body form-urlencoded content yourself, hacking it into ISO-8859-1 format manually, using something like

1:自己创建 POST 正文表单 urlencoded 内容,手动将其破解为 ISO-8859-1 格式,使用类似

function encodeLatin1URIComponent(str) {
    var bytes= '';
    for (var i= 0; i<str.length; i++)
        bytes+= str.charCodeAt(i)<256? str.charAt(i) : '?';
    return escape(bytes).split('+').join('%2B');
}

instead of encodeURIComponent().

而不是 encodeURIComponent()。

2: lose the ‘charset' and leave it submitting UTF-8 as normal, and make your servlet understand incoming UTF-8. This is generally best, but will mean mucking around with the servlet container config to make it choose the right encoding. For Weblogic this seems to mean using an <input-charset> elementin weblogic.xml. And by then you're looking at moving your whole app to UTF-8. Which is by no means a bad thing (non-Unicode-capable websites are sooo 20-century!) but may well be a lot of work.

2:丢失“字符集”并让它照常提交 UTF-8,并使您的 servlet 理解传入的 UTF-8。这通常是最好的,但也意味着要处理 servlet 容器配置以使其选择正确的编码。对于 Weblogic,这似乎意味着在 weblogic.xml 中使用 <input-charset> 元素。到那时,您正在考虑将整个应用程序移至 UTF-8。这绝不是一件坏事(不支持 Unicode 的网站都是 20 世纪!),但很可能需要大量工作。

回答by bobince

Actually just solved that, I needed to do:

实际上刚刚解决了这个问题,我需要这样做:

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

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

Which overrides the behaviour of adding application/x-www-form-urlencoded to the content-type in IE.

它覆盖了将 application/x-www-form-urlencoded 添加到 IE 中的内容类型的行为。

回答by Sebastian Alberoni

I was having similar problems, working in a content comments system in our Spanish Portal. What finally solved my problem, after many hours of searching, instead of messing with jQuery charset, that seems to use utf-8 no matter what, it was to decode from utf-8 back to ISO-8859-1 in the PHP that processed the ajax POST. In PHP there is a built in function, utf8_decode(), so the first thing I do with the comments string is this: $comentario = utf8_decode($_POST['comentario']);

我遇到了类似的问题,在我们的西班牙门户网站的内容评论系统中工作。经过数小时的搜索,最终解决了我的问题,而不是搞乱 jQuery 字符集,似乎无论如何都使用 utf-8,它是在处理的 PHP 中从 utf-8 解码回 ISO-8859-1 ajax POST。在 PHP 中有一个内置函数 utf8_decode(),所以我对注释字符串做的第一件事是: $comentario = utf8_decode($_POST['comentario']);

(and then I used nl2br() and htmlentities() PHP functions in order to prepare the text to be stored with html entities instead of special chars)

(然后我使用了 nl2br() 和 htmlentities() PHP 函数来准备要与 html 实体而不是特殊字符一起存储的文本)

Good Luck & Peace all over! Seba

祝你好运与和平!塞巴