使用Tornado回复Ajax请求

时间:2014-06-01 21:19:23

标签: jquery python ajax web-services tornado

我正在尝试使用由使用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;
});

所以,我的问题不是返回一些东西而是返回一些东西而不需要加载/重新加载页面。

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

看看这个,它可能对你有帮助。 https://github.com/zhanglongqi/TornadoAJAXSample

答案 1 :(得分:0)

年龄较晚,但是从其他人那里剔除了一个例子

#!/usr/bin/env python
"""Basic tornado ajax example"""

from __future__ import print_function
from __future__ import unicode_literals
import os.path
import json

import tornado.auth
import tornado.escape
import tornado.ioloop
from tornado.options import define, options
import tornado.web

PORT = 6098

define("port", default=PORT, help="run on the given port", type=int)

class AjaxHandler(tornado.web.RequestHandler):
    """Simple, ajax handler"""
    def get(self, *args, **kwargs):
        """get unlikely to be used for ajax"""
        self.write("Not allowed")
        self.finish()

    def post(self, *args):
        """Example handle ajax post"""
        dic = tornado.escape.json_decode(self.request.body)
        print(dic)
        # useful code goes here
        self.write(json.dumps({'status': 'ok', 'sent': dic}))
        self.finish()

class MainHandler(tornado.web.RequestHandler):
    """Simple example Main Handler"""
    def get(self):
        """main page set up"""
        self.render("tornado_index.html", messages=None)



class Application(tornado.web.Application):
    """Simple example App"""
    def __init__(self):
        handlers = [
            (r"/", MainHandler),
            (r"/(ajax)$", AjaxHandler),
        ]
        settings = dict(
            debug=True,
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "tornado_static")
        )
        tornado.web.Application.__init__(self, handlers, **settings)

def main():
    """start server"""
    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    print(PORT)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
<body>
Hello <div id="togo" contenteditable>World</div>

<div>Change the word "World" and look at console </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

function ajax_err(request, error) {
    console.log(request);
    console.log(error);
}
function ajax_ok(data) {
    console.log(data);
}
function togo_blur() {
    let r = {
        url : '/ajax',
        type : 'POST',
        data : JSON.stringify({new_val : $(this).text()}),
        dataType: 'json',
        success : ajax_ok,
        error: ajax_err
    }
    $.ajax(r);
}

$(document).ready(function() {
    $("#togo").on("blur", togo_blur);
});


</script>

</body>
</html>

答案 2 :(得分:0)

也很晚了,但这是另一个简单的示例,应该涵盖新旧浏览器:

HTML

<html>
<head>
<title>Simple Ajax Example</title>

<script language="Javascript">
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;

    // Mozilla/Safari/Chrome
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var form = document.forms['f1'];
    var word = form.word.value;
    qstr = 'w=' + escape(word);  // NOTE: no '?' before querystring
    return qstr;
}

function updatepage(str){
    document.getElementById("result").innerHTML = str;
}

</script>
</head>

<body>

<form name="f1">
  <p>Input: <input name="word" type="text">
  <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/")'></p>
  <div id="result"></div>  <!--NOTE div id HERE-->
</form>

</body>

</html>

Python3

import tornado.ioloop
import tornado.web
import tornado.options
from tornado.web import Application, url


class AjaxHandler(tornado.web.RequestHandler):

    def get(self):
        self.render('ajax.html')

    def post(self):
        word = self.get_argument('w')
        print('SUBMITTED: ', word)
        msg = '<p>Output: ' + word + '<p>'
        print('RETURNED: ', msg)
        self.write(msg)


if __name__ == "__main__":
    app = Application([
        url(r"/", AjaxHandler)],
        debug=True)
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

希望这会有所帮助!