微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 脚本通过 AJAX 调用将乱码的日语文本返回给 Javascript

如何解决Python 脚本通过 AJAX 调用将乱码的日语文本返回给 Javascript

在通过 FastCGI 运行 python3 的 IIS 服务器上,我试图获取一个 HTML 文件调用 python 脚本,该脚本返回一个包含日语文本的 JSON 文件。日文文本在返回时变成了 mojibake。使用 Chrome 的网络选项卡查看 test.py 文件的响应,我得到以下信息:

{ "text": "�e�X�g"}

python 脚本在名为 test.py 的文件中如下:

print("Content-type: application/json;\n")
print('{ "text": "テスト"}')    

调用 HTML 片段在这里

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript">
        var httpRequest;
        function makeRequest(){
            httpRequest = new XMLHttpRequest();
            if (!httpRequest){
                alert('Error: Cannot create an XMLHTTP instance');
                return false;
            }
            httpRequest.onreadystatechange = displayContents;
            httpRequest.open('GET','test.py');
            httpRequest.send();
        }
        function displayContents(){
            var text = '';
            if (httpRequest.readyState === XMLHttpRequest.DONE ){
                if (httpRequest.status === 200) {
                    var test = JSON.parse( httpRequest.responseText.trim() );
                    document.getElementById( "mydiv" ).innerHTML = test.text;  
                } else {
                    alert('There was a problem with the request. This can happen if there is no exchange rate data file named exchangerates.json');
                }
            }
        }
        </script>
        
<Meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<Meta http-equiv="Pragma" content="no-cache">
<title>Test Japanese</title>
</head>
<body id="thebody" onload="makeRequest();">
 <div id="mydiv" name="mydiv">testing Japanese...</div>
</body>
</html>

我尝试了很多方法来尝试解决问题,但无济于事。奇怪的是,如果我尝试从脚本生成这样的 JSON,它会出现乱码,但如果我将 JSON 写入文件并简单地让 HTML 文件检索 JSON 文件,它就可以正常工作。在这一点上,我将不胜感激。我的头发快用光了。

解决方法

我尝试了很多方法,但只有一种有用,那就是Json。

Python 代码:

import json
print("Content-type: application/json;")
print()
print(json.dumps({ "text": "テスト"}))    

当我直接访问py文件时,它显示:

enter image description here

然后我用ajax(代码和你的一样)来调用它。 enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。