我的服务器端代码是Perl CGI,可通过Ajax(XMLHttpRequest)访问。我的申请是多语言(英语/泰语)。
一个操作在服务器端读取泰语UTF-8编码文件,并简单地将嵌入在HTML框架中的内容返回给客户端。然后,我从XMLHttpRequest的responseText元素中获取此文本。当我在应用程序中显示结果字符串时,在textarea或div中,文本显示乱码。非泰语文本正确显示。
我可以直接从浏览器调用CGI操作并正确显示内容,因此问题似乎与从响应中提取内容并将其存储在我的JavaScript字符串变量中的过程有关。我在这项任务中尝试过各种类型的转换,但是从评论中删除了详细信息,因为评论者认为这些转换不相关。
应用程序html中的编码正确设置为UTF-8。
function getAbstract_API(projectYear,projectId,english_flag, successfunction, errorfunction)
{
var requestString = url + "?action=getabstract&projectyear=" + projectYear;
requestString += "&projectid=" + projectId +
"&english_flag=" + english_flag;
var request = new XMLHttpRequest();
request.open("Get",requestString);
request.send(null);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
if (request.status == 200)
{
var response = request.responseText;
var errorpattern = /\w*ERROR/;
if (response.match(errorpattern))
{
var errcode = extractErrorCode(response);
var messagedetail = getMessageDetail(errcode);
showI18NAlert(messagedetail);
if (errorfunction)
errorfunction();
return false;
}
abstractText = response;
if (successfunction)
successfunction();
}
else
{
showI18NAlert('requesterror_msg');
}
}
} /* end callback function */
}
abstractText是一个全局变量,它应该保存返回的文本,以便显示。
sub getAbstract
{
my $Projectid = $cgi->param('projectid');
my $Projectyear = $cgi->param('projectyear');
my $English_flag = $cgi->param('english_flag');
if (!$Projectid)
{
showError("Missing required parameter 'projectid'");
}
if (!$Projectyear)
{
showError("Missing required parameter 'projectyear'");
}
if (!$English_flag)
{
$English_flag = 'true';
}
# get the name of the abstract file
my $sqlcommand = "select ";
if ($English_flag eq 'true')
{
$sqlcommand .= "abstract_en_file ";
}
else
{
$sqlcommand .= "abstract_th_file ";
}
$sqlcommand .= "from projects where id=$Projectid;";
logentry("About to execute: |$sqlcommand|\n");
my $stmt = $gDbh->prepare($sqlcommand);
my $numrows = $stmt->execute;
$gSqlError= $gDbh->err;
$gSqlErrorStr = $gDbh->errstr;
if ($gSqlError != 0)
{
showError($gSqlErrorStr); # dies after sending the error
}
if ($numrows != 1)
{
showError("No project found with id $Projectid");
}
my ($filename) = $stmt->fetchrow_array;
if (($English_flag eq 'false') && ($filename eq 'NULL'))
{
returnApplicationError("Cannot read abstract file: $filename\nERRORCODE|112|\n");
}
my $path = "$homedir/$gDocLocation/Abstracts/$filename";
my $fh;
if (!open($fh, '<',$path))
{
returnApplicationError("Cannot read abstract file: $path\nERRORCODE|111|\n");
}
my $filecontents = '';
my @lines = <$fh>;
foreach my $line (@lines)
{
$filecontents .= "$line";
}
close $fh;
showSuccess("~ABSTRACT~\n$filecontents");
# showSuccess returns the passed text within an html document
}
请不要浪费时间批评我的风格或习语。我知道有业余元素。我一边走一边学习这个!
感谢。