flask从jquery接收var

时间:2017-05-12 21:51:09

标签: jquery ajax flask

我觉得这是非常基本的东西,听起来应该是这样。但我无法在网上找到这个。设置很简单: 我有一个变量foo = 1,现在我想做的就是将其发送到我的app.py。我知道我需要AJAX,所以我也在那里。我认为我需要做的事情是这样的:

js

$(function() {
        $('#btn').click(function() {
            var answer = 1
        $.ajax({
            url: '/checkAnswer',
            data: answer,
            type: 'GET',
            success: function(data) {
                console.log(data);
            },
            error: function(error) {
                console.log(error);
            }
        });
        });
        });

py

@app.route('/checkAnswer', methods=['GET', 'POST'])
def checkAnswer():
    try:
        answer = request.data
        if answer == 1:
            return 'ham'
        else:
            return answer

    except Exception as e:
        return 'foo bar'

1 个答案:

答案 0 :(得分:1)

最好在您传输数据时使用import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', home: new ExampleWidget(), ); } } /// Opens an [AlertDialog] showing what the user typed. class ExampleWidget extends StatefulWidget { ExampleWidget({Key key}) : super(key: key); @override _ExampleWidgetState createState() => new _ExampleWidgetState(); } /// State for [ExampleWidget] widgets. class _ExampleWidgetState extends State<ExampleWidget> { final TextEditingController _controller = new TextEditingController(); @override Widget build(BuildContext context) { return new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new TextField( controller: _controller, decoration: new InputDecoration( hintText: 'Type something', ), ), new RaisedButton( onPressed: () { showDialog( context: context, child: new AlertDialog( title: new Text('What you typed'), content: new Text(_controller.text), ), ); }, child: new Text('DONE'), ), ], ); } } 代替Launching lib/main.dart on Android SDK built for x86 in debug mode... Built build/app/outputs/apk/app-debug.apk (21.5MB). I/flutter ( 5187): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter ( 5187): The following assertion was thrown building InputDecorator(decoration: InputDecoration(hintText: I/flutter ( 5187): "Type something"); baseStyle: null; isFocused: false; isEmpty: true; dirty): I/flutter ( 5187): No Material widget found. I/flutter ( 5187): InputDecorator widgets require a Material widget ancestor. I/flutter ( 5187): In material design, most widgets are conceptually "printed" on a sheet of material. In Flutter's I/flutter ( 5187): material library, that material is represented by the Material widget. It is the Material widget I/flutter ( 5187): that renders ink splashes, for instance. Because of this, many material library widgets require that I/flutter ( 5187): there be a Material widget in the tree above them. I/flutter ( 5187): To introduce a Material widget, you can either directly include one, or use a widget that contains I/flutter ( 5187): Material itself, such as a Card, Dialog, Drawer, or Scaffold. I/flutter ( 5187): The specific widget that could not find a Material ancestor was: I/flutter ( 5187): InputDecorator(decoration: InputDecoration(hintText: "Type something"); baseStyle: null; I/flutter ( 5187): isFocused: false; isEmpty: true) I/flutter ( 5187): The ownership chain for the affected widget is: I/flutter ( 5187): InputDecorator ← AnimatedBuilder ← Listener ← _GestureSemantics ← RawGestureDetector ← I/flutter ( 5187): GestureDetector ← TextField ← Column ← ExampleWidget ← _ModalScopeStatus ← ⋯ I/flutter ( 5187): I/flutter ( 5187): When the exception was thrown, this was the stack: I/flutter ( 5187): #0 debugCheckHasMaterial.<anonymous closure> (package:flutter/src/material/debug.dart:26) I/flutter ( 5187): #2 debugCheckHasMaterial (package:flutter/src/material/debug.dart:23) I/flutter ( 5187): #3 InputDecorator.build (package:flutter/src/material/input_decorator.dart:334) ... <output omitted> I/flutter ( 5187): (elided one frame from class _AssertionError) I/flutter ( 5187): ════════════════════════════════════════════════════════════════════════════════════════════════════ I/flutter ( 5187): Another exception was thrown: No Material widget found. 。此外,POSTGET promises通常更清晰,更有用的回调。

js:

done

py:

fail

$(function() { $('#btn').click(function() { var answer = 1 $.ajax({ url: '/checkAnswer', data: { answer: answer }, type: 'POST' }).done(function(data) { console.log(data); }).fail(function(error) { console.log(error); }); }); 是最好的情况。但是,在过去使用@app.route('/checkAnswer', methods=['POST']) def checkAnswer(): try: answer = request.form['answer'] if 'answer' in request.form else None if answer == 1: return 'ham' else: return answer except Exception as e: return 'foo bar' 发布数据时,我必须这样做以获取数据:

request.form['answer']

因此,我建议发送JSON:

JS:

ajax

吡啶:

answer = request.form.getlist('answer')[0]

注意:在ajax请求中设置内容类型很重要,好像没有设置$(function() { $('#btn').click(function() { var answer = 1 $.ajax({ url: '/checkAnswer', data: JSON.stringify({'answer': answer}), type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', }).done(function(data) { console.log(data); }).fail(function(error) { console.log(error); }); }); returns None