1

我在 struts 2 应用程序中发送标题中的自定义错误消息。我通过在 struts.xml 文件中添加一个全局结果来完成它,例如:

<global-results>
    <result name="badDataError" type="httpheader">
       <param name="status">500</param>
       <param name="headers.errorMessage">${exception.message}</param>
    </result>
</global-results>

<global-exception-mappings>
    <exception-mapping result="badDataError" exception="mypackage.BadDataException" />
</global-exception-mappings>

所以当我抛出一个异常时

throw new BadDataException("my error message");

然后该消息包含在文件的标题中,因此可以在 json 中作为错误读取:

$.ajax(
    { 
        url: ...,
        type: "POST",
        data: ...,
        success: function(data, textStatus) {
            alert("save works");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var errorMessage = XMLHttpRequest.getResponseHeader('errorMessage'); 
            var message = "There has been an error";
            if (errorMessage != null){
                message = message + ':<br/>'+errorMessage;
            }
            alert(message);
        },
        dataType: "json"
    }
);    

这可行,但是每当我发送带有任何特殊字符(例如á éñ ...)的消息时,它都不会在警报中正确显示,也不会通过使用console.log()显示变量来正确显示,尽管如果我在那里使用firebug 消息正确显示,好像它没有在 javascript 中使用正确的编码。

我试图在ajax调用中设置

contenType: 'application/x-www-form-urlencoded; charset=UTF-8'
or
contenType: 'application/x-www-form-urlencoded; charset=ISO-8859-1'

但没有任何成功。

我如何知道错误消息和标头使用了哪种编码,并且能够为它选择不同的编码?

谢谢。

4

1 回答 1

0

此处定义了非 ASCII 文本的标头字段编码:http ://www.ietf.org/rfc/rfc2047.txt

阅读起来并不难,在那里你会找到答案。编码标头字段的示例是

 =?iso-8859-1?q?this=20is=20some=20text?=
于 2012-10-31T19:33:03.407 回答