如何在Rails的HTTP头中编码/解码UTF-8 ?

时间:2022-02-04 11:17:03

I am using the "insert Rails flash messages into HTTP headers to show Ajax response errors" pattern, like this:

我正在使用“向HTTP头中插入Rails flash消息以显示Ajax响应错误”模式,如下所示:

Controller:

控制器:

 def flash_as_header
   return unless request.xhr?
   [:error, :warning, :notice].each do |type|
    if flash[type]
     response.headers["X-Ajax-#{type.to_s.humanize}"] = flash[type]
    end
   end
 end

JQuery:

JQuery:

 $(document).ajaxComplete(function(response, status, xhr) {
    var types = ["Error", "Notice", "Warning"];
    for (i = 0, l = types.length; i < l; ++i) {
        msg = status.getResponseHeader("X-Ajax-" + types[i]);
        if(msg) {
            break;
        }
    }
    if(msg) {
        $('.flash-error').text(msg).removeClass('is-hidden');
    }
 });

This works, but I am running into character encoding issues. The flash messages contain UTF-8 special characters, and the destination HTML document is UTF-8.

这是可行的,但是我遇到了字符编码问题。flash消息包含UTF-8特殊字符,目标HTML文档是UTF-8。

Here is a sample string, as it should appear:

这是一个示例字符串,应该是:

Användare

This is how it in the HTTP response (correct: %C3%A4 is ä):

这是HTTP响应中的方法(正确:%C3%A4是a):

X-Ajax-Error:Anv%C3%A4ndare

And this is how that outputs in the HTML document:

这就是HTML文档的输出:

Användare

That is consistent with this table (http://www.i18nqa.com/debug/utf8-debug.html) which says that "the problem is being caused by UTF-8 bytes being interpreted as Windows-1252 (or ISO 8859-1) bytes."

这与这个表是一致的(http://www.i18nqa.com/debug/utf8-debug.html),它说“问题是由于UTF-8字节被解释为Windows-1252(或ISO 8859-1)字节。”

I am unsure how & where to fix this- in the JQuery function, in the Rails Controller, or in the HTML template?

我不确定在JQuery函数、Rails控制器或HTML模板中如何以及在哪里修复这个问题?

1 个解决方案

#1


4  

A combination of escaping & decoding in the Javascript has worked:

Javascript中转义和解码的结合已经奏效:

I changed this:

我改变了:

 $('.flash-error').text(msg).removeClass('is-hidden');

to this:

:

$('.flash-error').text(decodeURIComponent(escape(msg))).removeClass('is-hidden');

The output is now correct.

输出现在是正确的。

#1


4  

A combination of escaping & decoding in the Javascript has worked:

Javascript中转义和解码的结合已经奏效:

I changed this:

我改变了:

 $('.flash-error').text(msg).removeClass('is-hidden');

to this:

:

$('.flash-error').text(decodeURIComponent(escape(msg))).removeClass('is-hidden');

The output is now correct.

输出现在是正确的。