有人可以向我解释我得到的错误吗?

时间:2012-08-29 16:56:24

标签: javascript python ajax xmlhttprequest

我有一个CGI脚本,它导入cgi,创建一个访问器函数,然后尝试查找变量。功能是:

cgi_form = cgi.FieldStorage()

def get_cgi(field, default=''):
    if cgi_form.has_key(field):
        return cgi_form[field].value
    else:
        return default

可能没有必要。但是当我尝试将它用于电子邮件时,我试图从XHR发送的一个字段,它出错了。触发问题的代码行是:

sys.stderr.write('email: ' + get_cgi('email'))

Apache日志有:

[Wed Aug 29 11:25:33 2012] [error] [client ::1] Traceback (most recent call last):, referer: http://localhost/professional/calendar-todo/
[Wed Aug 29 11:25:33 2012] [error] [client ::1]   File "/Users/jonathan/mirror/professional/calendar-todo/create_account.cgi", line 26, in <module>, referer: http://localhost/professional/calendar-todo/
[Wed Aug 29 11:25:33 2012] [error] [client ::1]     sys.stderr.write('email: ' + get_cgi('email')), referer: http://localhost/professional/calendar-todo/
[Wed Aug 29 11:25:33 2012] [error] [client ::1]   File "/Users/jonathan/mirror/professional/calendar-todo/create_account.cgi", line 21, in get_cgi, referer: http://localhost/professional/calendar-todo/
[Wed Aug 29 11:25:33 2012] [error] [client ::1]     if cgi_form.has_key(field):, referer: http://localhost/professional/calendar-todo/
[Wed Aug 29 11:25:33 2012] [error] [client ::1]   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cgi.py", line 580, in has_key, referer: http://localhost/professional/calendar-todo/
[Wed Aug 29 11:25:33 2012] [error] [client ::1] TypeError: not indexable, referer: http://localhost/professional/calendar-todo/
[Wed Aug 29 11:25:33 2012] [error] [client ::1] Premature end of script headers: create_account.cgi, referer: http://localhost/professional/calendar-todo/

我试图模仿的客户端代码是:

document.getElementById('create_account_button').onclick = function()
    {
    var request = new XMLHttpRequest();
    request.open('POST', 'create_account.cgi');
    request.setRequestHeader('Content-Type', 'text/plain');
    request.send('email=' + encodeURIComponent(document.getElementById('create_email').value) + '&password=' + encodeURIComponent(document.getElementById('create_password').value) +  '&password_hint=' + encodeURIComponent(document.getElementById('create_password_hint').value));
    load_from_request(request);
    return false;
    }

我是否通过JavaScript将内容正确地发送到XHR?为什么在Python中调用get_cgi('email')来调用“TypeError:not indexable”,我该怎么做才能纠正它?

1 个答案:

答案 0 :(得分:2)

第一个问题是请求标头未设置为request.setRequestHeader("Content-type","application/x-www-form-urlencoded");。 对于过早的标题问题,它是相同的概念。在打印任何数据之前确定您正在打印内容标题。

print "Content-Type: text/html" 

通常我会将内容类型打印输出放在我的代码顶部,这样我就可以看到任何被发送回浏览器的内容。这样,当您的代码错误消失时,您至少会看到问题所在。