Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 使用Tornado回复Ajax请求_Jquery_Python_Ajax_Web Services_Tornado - Fatal编程技术网

Jquery 使用Tornado回复Ajax请求

Jquery 使用Tornado回复Ajax请求,jquery,python,ajax,web-services,tornado,Jquery,Python,Ajax,Web Services,Tornado,我正在尝试使用ajax(POST)完成一个非常简单的表单提交示例,该示例由使用Tornado的Python函数处理 当它工作时,我可以返回响应,我的主要目标是在不重新加载新/相同页面的情况下返回一些数据。只传回一些数据,这些数据应该由jQuery处理 以下是我的Python代码: class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/(hap

我正在尝试使用ajax(POST)完成一个非常简单的表单提交示例,该示例由使用Tornado的Python函数处理

当它工作时,我可以返回响应,我的主要目标是在不重新加载新/相同页面的情况下返回一些数据。只传回一些数据,这些数据应该由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;
});
$(函数(){
变量文本=“”
$('.error').hide();
$(“.add_post”)。单击(函数(){
text=$(“输入消息”).val();
如果(文本==“”){
$(“label#name_error”).show();
$(“输入文本”).focus();
返回false;
}
$.ajax({
类型:“POST”,
数据:“消息=”+文本,
成功:功能(数据){
$(“#左菜单”).html(“”);
$(“#message”).html(“已提交联系人表单!”).append(我们很快就会联系。

”).hide() .fadeIn(1500,函数(){ $(“#消息”)。追加(“”); }); } }); }); 返回false; });
所以,我的问题不是返回一些东西,而是返回一些不需要加载/重新加载页面的东西


谢谢你的帮助。

看看这个,它可能会对你有所帮助。

看看这个,它可能会对你有所帮助。

年代较晚,但有一个例子是从其他各种例子中挑选出来的

#!/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


你好,世界
更改单词“World”并查看控制台
函数ajax\u err(请求、错误){
控制台日志(请求);
console.log(错误);
}
函数ajax\u ok(数据){
控制台日志(数据);
}
函数togo_blur(){
设r={
url:“/ajax”,
键入:“POST”,
数据:JSON.stringify({new_val:$(this.text()}),
数据类型:“json”,
成功:好的,
错误:ajax\u err
}
$.ajax(r);
}
$(文档).ready(函数(){
美元(“#多哥”)。关于(“模糊”,多哥模糊);
});

年代较晚,但有一个例子是从其他各种例子中挑选出来的

#!/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


你好,世界
更改单词“World”并查看控制台
函数ajax\u err(请求、错误){
控制台日志(请求);
console.log(错误);
}
函数ajax\u ok(数据){
控制台日志(数据);
}
函数togo_blur(){
设r={
url:“/ajax”,
键入:“POST”,
数据:JSON.stringify({new_val:$(this.text()}),
数据类型:“json”,
成功:好的,
错误:ajax\u err
}
$.ajax(r);
}
$(文档).ready(函数(){
美元(“#多哥”)。关于(“模糊”,多哥模糊);
});

也过时了,但这里有另一个简单的例子,应该涵盖新旧浏览器:

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>

简单的Ajax示例
函数xmlhttpPost(strURL){
var xmlHttpReq=false;
var self=这个;
//Mozilla/Safari/Chrome
if(window.XMLHttpRequest){
self.xmlHttpReq=新的XMLHttpRequest();
}
//即
else if(window.ActiveXObject){
self.xmlHttpReq=新的ActiveXObject(“Microsoft.XMLHTTP”);
}
self.xmlHttpReq.open('POST',strURL,true);
self.xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange=函数(){
if(self.xmlHttpReq.readyState==4){
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
函数getquerystring(){
var form=document.forms['f1'];
var word=form.word.value;
qstr='w='+转义(word);//注意:在querystring之前没有“?”
返回qstr;
}
函数更新页(str){
document.getElementById(“结果”).innerHTML=str;
}
输入:

蟒蛇3

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()
导入tornado.ioloop
导入tornado.web
导入tornado.options
从tornado.web导入应用程序,url
AjaxHandler类(tornado.web.RequestHandler):
def get(自我):
self.render('ajax.html')
def post(自我):
word=self.get\u参数('w')
打印('已提交:',word)
msg='输出:'+word+''
打印('返回:',消息)
self.write(msg)
如果名称=“\uuuuu main\uuuuuuuu”:
app=应用程序([
url(r/,AjaxHandler)],
debug=True)
app.listen(8888)
tornado.ioloop.ioloop.current().start()

希望这有帮助

老化也很晚,但这里有另一个简单的例子,应该涵盖新旧浏览器:

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>

简单的Ajax示例
函数xmlhttpPost(strURL){
var xmlHttpReq=false;
var self=这个;
//Mozilla/Safari/Chrome
if(window.XMLHttpRequest){
self.xmlHttpReq=新的XMLHttpRequest();
}
//即
else if(window.ActiveXObject){
self.xmlHttpReq=新的ActiveXObject(“Microsoft.XMLHTTP”);
}
self.xmlHttpReq.open('POST',strURL,true);
self.xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange=函数(){
if(self.xmlHttpReq.readyState==4){
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
函数getquerystring(){
var form=document.forms['f1'];
var word=form.word.value;
qstr='w='+转义(word);//注意:在querystring之前没有“?”
返回qstr;
}
函数更新页(str){
document.getElementById(“结果”).innerHTML=str;
}
输入:

蟒蛇3

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()
导入tornado.ioloop
导入tornado.web
导入tornado.options
从tornado.web导入应用程序,url
AjaxHandler类(tornado.web.RequestHandler):
def get(自我):
self.render('ajax.html')
def post(自我):
word=self.get\u参数('w')
打印('已提交:',word)
msg='输出:'+word+''
打印('返回:',消息)
self.write(msg)
如果名称=“\uuuuu main\uuuuuuuu”:
app=应用程序([
url(r/),Ajax