简体   繁体   English

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

[英]How to encode/decode UTF-8 in HTTP headers in Rails?

I am using the "insert Rails flash messages into HTTP headers to show Ajax response errors" pattern, like this: 我正在使用“将Rails flash消息插入HTTP标头以显示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. 闪存消息包含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是ä):

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模板中如何以及在何处修复此问题?

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. 输出现在是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM