XMLHttpRequest以UTF-8改变文本

时间:2013-07-01 13:00:14

标签: javascript ajax unicode xmlhttprequest

在处理巨大的XML客户端时,遇到了以下问题:一些unicode字符被不可读的序列替换,因此服务器无法解析该XML。像这样测试:

var text = new XMLSerializer().serializeToString(xmlNode);
console.log(text);
var req = new XMLHttpRequest();
req.open('POST', config.saveUrl, true);
req.overrideMimeType("application/xml; charset=UTF-8");
req.send(text);

记录仍然显示正确的字符串:

<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />

在请求(Chrome开发工具)和服务器端,它看起来像这样修改:

<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />

XML文件的原始编码也是UTF-8。使用jQuery时的行为绝对相同。

2 个答案:

答案 0 :(得分:0)

  1. 检查overrideMimeType是否使用大写&#34; UTF-8&#34;或小写&#34; utf-8&#34;
  2. 确保javascript计算前的字符串是utf-8(检查页面charset)
  3. 使用escape / encodeURIComponent / decodeURIComponent将其发送到服务器并在服务器上取消它
  4. 尝试application / x-www-form-urlencoded ans send xml like plain text
  5. P.S。修改后的字符串在ISO-8859-15

答案 1 :(得分:0)

似乎这样做了。

我这里有数据json参数,包含一个字符串“Lääke”(芬兰语单词),我通过ajax发送到服务器。

这不起作用,服务器应用程序没有收到'ää'但是'??':

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    status = this.responseText;
    if (status === "OK") {
        window.location.assign("ackok.html");
    }
    else {
        window.location.assign("ackerror.html");
    }
  }
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);    
xhttp.send();

这确实有效,服务器收到'ää':

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    status = this.responseText;
    if (status === "OK") {
        window.location.assign("ackok.html");
    }
    else {
        //orderStatusElement[0].innerHTML = "<b>Palvelimella jokin meni vikaan. Yritä myöhemmin uudelleen </b>";
        window.location.assign("ackerror.html");
    }
  }
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
xhttp.send();