有人能向我解释一下我犯的一个错误吗

Could someone explain to me an error I am getting?

本文关键字:错误 一个 解释 一下      更新时间:2023-09-26

我有一个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",我该怎么做才能纠正这个问题?

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

print "Content-Type: text/html" 

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

相关文章: