【发布时间】:2011-06-29 09:40:13
【问题描述】:
我目前正在做一个我们以前使用 Django 的项目。然而,事实证明这对于我们的需求来说有点重量级,所以我们将项目转移到使用cherrypy,因为我们只需要处理请求。
我的问题是这样的。当用户单击提交时,我在 html 页面 (index.html) 上有一个表单,执行以下 jQuery 函数。
$(document).ready(function() {
$("#loginform").submit(function() {
var request_data = {username:$("#username").val(),password:"test"};
$.post('/request',request_data, function(data) {
$("#error").html(data['response']);
});
return false;
});
});
这很好用。 下面的 Cherrypy 方法应该获取请求数据,但它似乎没有被执行。这是请求的 Cherrypy 方法。
@cherrypy.expose
def request(self, request_data):
print "Debug"
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(dict(response ="Invalid username and/or password"))
这只是一种测试方法,我希望看到“调试”出现在终端窗口中,并在单击提交按钮后在网页上显示错误消息
在发出请求后,我在终端中收到此消息:
"POST /request HTTP/1.1" 404 1254 "http://127.0.0.1:8080/" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"
这表示它找不到请求方法。我能想到的只是它与参数有关。
由于我是cherrypy的新手,我希望这很简单,我缺少任何指针都会很棒。
PS:以下工作,但我需要能够将多个数据传递给cherrypy。 (cherrypy 参数更改为 username 以允许它工作)
$(document).ready(function() {
$("#loginform").submit(function() {
$.post('/request',{username:$("#username").val()}, function(data) {
$("#error").html(data['response']);
});
return false;
});
});
在此先感谢您对此问题的任何帮助或指导。
这是我完整的cherrypy文件。
import cherrypy
import webbrowser
import os
import simplejson
import sys
from backendSystem.database.authentication import SiteAuth
MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")
class LoginPage(object):
@cherrypy.expose
def index(self):
return open(os.path.join(MEDIA_DIR, u'index.html'))
@cherrypy.expose
def request(self, request_data):
print "Debug"
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(dict(response ="Invalid username and/or password"))
config = {'/media': {'tools.staticdir.on': True, 'tools.staticdir.dir': MEDIA_DIR, }}
root = LoginPage()
# DEVELOPMENT ONLY: Forces the browser to startup, easier for development
def open_page():
webbrowser.open("http://127.0.0.1:8080/")
cherrypy.engine.subscribe('start', open_page)
cherrypy.tree.mount(root, '/', config = config)
cherrypy.engine.start()
【问题讨论】:
-
您应该在下面发布解决方案作为答案