我正在尝试使用由使用 Tornado 的 Python 函数处理的 ajax (POST) 来做一个非常简单的表单提交示例。
虽然它正在工作,因此我可以返回响应,但我的主要目标是返回一些数据而无需重新加载新的/相同的页面。只传回一些应该由 jQuery 处理的数据。
这是我的 Python 代码:
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/(happiness)", Happiness),
]
settings = {
"template_path": Settings.TEMPLATE_PATH,
"static_path": Settings.STATIC_PATH,
}
tornado.web.Application.__init__(self, handlers, **settings)
class Happiness(tornado.web.RequestHandler):
def get(self, call):
resp = valid_calls[call]
if resp:
template, ctx = resp()
self.render(template, ctx=ctx)
def post(self, source):
text = self.get_argument('message')
self.write(text)
这是我的 jQuery 代码:
$(function() {
var text = ''
$('.error').hide();
$(".add_post").click(function() {
text = $("input#message").val();
if (text == "") {
$("label#name_error").show();
$("input#text").focus();
return false;
}
$.ajax({
type: "POST",
data: "message=" + text,
success: function(data) {
$('#left-menu').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>").append("<p>We will be in touch soon.</p>").hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='../images/arrow-up.gif' />");
});
}
});
});
return false;
});
因此,我的问题不是返回某些内容,而是返回某些内容而不需要加载/重新加载页面。
感谢您的帮助。
请您参考如下方法:
看看这个,它可能对你有帮助。 https://github.com/zhanglongqi/TornadoAJAXSample
