Skip to main content
 首页 » 编程设计

Python Unicode ajax 表单发布错误

2025年05月04日27三少

我遇到了 python 的 n00b 问题,我在这里搜索了一段时间,但找不到合适的解决方案...

我得到了一个 utf8 表单,我将它通过 ajax 发布到 python 页面。我阅读了带有 utf-8 字符集的 json simplejson。

只要没有混合的 utf8 和拉丁字符,如 ?!; 等,文本就没问题......

UnicodeDecodeError:“ascii”编解码器无法解码位置 0 中的字节 0xd7:序号不在范围内 (128)

commentjsonarray = simplejson.loads(commentjson, encoding='utf-8') 

我尝试了很多东西,但我无法让它工作。 帮助。

只是为您提供了更多帮助代码的更新,谢谢

commentjson = request.POST['commentObj']

commentjsonarray = simplejson.loads(commentjson, encoding='utf-8') 
program = get_object(Program, commentjsonarray['programid']) 
userget = get_object(User, commentjsonarray['userid']) 
#get user avatar from usermeta 
usermeta = get_object(UserMeta, 'user_id = ',userget.key()) 
commenttext = commentjsonarray['walltext'] 
from django.utils.encoding import smart_unicode,force_unicode,smart_str 
 
commenttext = smart_str(commenttext) 
 
newcomment = db_create(Wall, user_avatarurl=str(usermeta.avatarurlsmall),user_fullname=str(''+userget.first_name+' '+userget.last_name),user_idstring=str(userget.key()),text = str(commenttext) , program_id = program.key() , user_id = userget.key()) 

以上是python部分。 这是javascript:

var walltext = $('walltext').value 
 
 var commentObj = {"walltext": ""+walltext+"", "programid": programid, "userid": userid}; 
 var commentJSON = encodeURIComponent(Object.toJSON(commentObj)); 
if (walltext != '' || walltext == 'type here' || walltext.length > 0) { 
 
    new Ajax.Request('/wall/new', { 
        method: 'post', 
        encoding: 'UTF-8', 
        parameters: 'commentObj=' + commentJSON, 
        onSuccess: function(request){ 
            var msg = request.responseText.evalJSON(); 
            if (msg) { 
 
                var structure = '<div id="' + msg.msgid + '"><img src="' + msg.avatarurl + '" width="18" height="18"> ' + msg.username + ':' + msg.text + '<div id="frontSepLine"></div></div>'; 
 
                //$('programwall').insert({bottom:structure}); 
                refreshWall(msg.programid); 
 
                $('walltext').value = 'type here'; 
 
                var objDiv = document.getElementById("programwall"); 
                objDiv.scrollTop = objDiv.scrollHeight; 
 
 
            } 
 
 
 
        } 
    }); 

请您参考如下方法:

你所描述的情况对我来说很好(使用 Python 2.6 上的标准库 json),无论是否使用显式编码(utf-8 编码的字节串都不需要) ,因为 utf-8 是这里的默认值):

>> s = u'{"valá":"macché?!"}'.encode('utf8') 
>>> json.loads(s) 
{u'val\xe1': u'macch\xe9?!'} 
>>> json.loads(s, encoding='utf-8') 
{u'val\xe1': u'macch\xe9?!'} 

还有 simplejson 2.1.1(在 2.6 上确实是多余的,但是,好吧;-):

>>> import simplejson 
>>> s = u'{"valá":"macché?!"}'.encode('utf8') 
>>> simplejson.loads(s) 
{u'val\xe1': u'macch\xe9?!'} 
>>> simplejson.loads(s, encoding='utf-8') 
{u'val\xe1': u'macch\xe9?!'} 

您能更准确地描述您的问题吗?您对触发错误的原因的描述,即“只要没有混合的 utf8 和拉丁字符,如 ?!; 等”的相反,不会造成任何问题 - 那么向我们展示最小的例子怎么样 < em>是否重现了您的问题?