【问题标题】:How to send a string to my server using JSON? (tornado)如何使用 JSON 将字符串发送到我的服务器? (龙卷风)
【发布时间】:2017-08-07 18:28:31
【问题描述】:

所以我有一个 HTML 输入框,它在单击提交按钮后调用 javascript 函数。我想将用户在该输入框中输入的数据发送到我的龙卷风服务器。我对这一切都很陌生,并且尝试了一些不同的选择,但似乎都没有奏效。使用此代码,我收到 405(不允许方法)错误。这是我现在拥有的:

var myData = hello

function pushURL(){

    var passThis = {
        apples : myData
    }

    $.ajax({
        url: "/",
        type: 'POST',
        contenttype: 'application/json; charset=utf-8',
        data : JSON.stringify(passThis),
        dataType: 'JSON'
    });
}

这是我的龙卷风脚本:

import tornado.ioloop
import tornado.web
import json

#Utility libraries
import os.path

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

#This tells tornado where to find static files
settings = dict(
    template_path = os.path.join(os.path.dirname(__file__), "templates"),
    static_path = os.path.join(os.path.dirname(__file__), "static"),
    debug = True
)

# r"/" == root website address
application = tornado.web.Application([
    (r"/", MainHandler)
],**settings)

#Start the server at port n
if __name__ == "__main__":
    print('Server Running...')
    print('Press ctrl + c to close')
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

我将需要在一些服务器端 python 脚本中使用该字符串,但现在我只想在用户单击提交时看到它打印到控制台。任何帮助将不胜感激。另外,如果你能用一些 ELI5 术语来解释,那就太好了。

【问题讨论】:

    标签: javascript jquery python json tornado


    【解决方案1】:

    您正在将数据作为 post 请求从前端发送到您的索引路由,因此您必须在 MainHandler 类中定义一个 post 方法。 请参考此文档here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2013-10-26
      • 2010-12-10
      相关资源
      最近更新 更多