我目前正在做一个我们以前使用过Django的项目。然而,事实证明,这对于我们的需求来说有点太重了,所以我们将项目转移到使用cherrypy,因为我们只需要处理请求。
我的问题是。我在html页面上有一个表单(index.html),当用户单击submit时,将执行以下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"))这只是一个测试方法,我希望看到'Debug‘出现在终端窗口中,并在单击submit按钮后在网页上显示错误消息
在终端中,我在发出请求后收到以下消息:
"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()发布于 2011-07-06 21:43:55
我已经找到了解决这个问题的办法。JQuery:
$(document).ready(function() {
$("#loginform").submit(function() {
$.post('/request',{username:$("#username").val(),password:"test"},
function(data) {
$("#error").html(data['response']);
});
return false;
});
});然后在cherrypy方法中,我这样做:
def request(self, **data):
# Then to access the data do the following
print data['<keyValue'] # In this example I would type print data['username']真的很简单,一个只见树木不见森林的例子。希望这对其他人有帮助。
https://stackoverflow.com/questions/6518595
复制相似问题