jquery ajax

Post方式

获取input value的几种方式:

$(" #name ").val()
$(" input[ name='name' ] ").val()
$(" input[ type='text' ] ").val()
$(" input[ type='text' ]").attr("value")
、、、

坑1:如果没有$('#submit').click(function()动作的话,就只能获取input的预设value,如果没有预设则返回空

<body>
<p>jquery ajax</p>
<form id="form1">
    <input type="text" id="name">
    <input type="submit" value="Submit form" id="submit" />
</form>
<script type="text/javascript">
    $('#submit').click(function(){
        var data={}
        data['name'] = $('#name').val();
        $.ajax({
            type: 'POST',
            url: "/trans1",
            data: JSON.stringify(data),
            contentType: 'application/json; charset=UTF-8',
            dataType: 'json',
            success: function(data) {
                alert(data)
            },
            error: function(xhr, type) {
            }
        });
    });
</script>
</body>

坑2:获取json数据可使用get_json()方法

@app.route('/trans1', methods=['post'])
def trans1():
    name = request.get_json('name')
    print(name['name'])
    return jsonify(name['name'] + '233333')

另一种写法

坑3:input 的类型只能为button不能为submit只能为button,否则点击button会执行表单action,不会走jquery异步

<script type="text/javascript">
    $('#submit').click(function(){
        var data={}
        data['name'] = $('#name').val();
        var url = "/trans1";
        $.post(url,JSON.stringify(data),function(data){alert(data)},'json');
    });
</script>

Flask WTF表单

from flask_wtf import Form
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired


class TestForm(Form):
    name = StringField('name', validators=[DataRequired()])
    submit = SubmitField(label='submit')


@app.route('/wtform', methods=['get','post'])
def wtform():
    form = TestForm()
    name = form.name.data
    print(name)
    return render_template('wtform.html', form=form, name=name)

坑4: {{form.hidden_tag()}}是flask防止csrf的机制,在config.py里配置SECRET_KEY = '************',在view.py中引入app.config.from_pyfile('config.py')

<body>
<form action="{{ url_for('wtform') }}" method="post">
    {{form.hidden_tag()}}
    <p>
        {{form.name}}<br>
        {{ form.submit }}
    </p>
    <p>Hello, {{ name }}</p>
</form>
</body>

XMLHttpRequest

Post

<html>
  <head>
    <title>Practice AJAX</title>
    <script type="text/javascript">
      function do_ajax() {
        var req = new XMLHttpRequest();
        var result = document.getElementById('result');
        req.onreadystatechange = function()
        {
          if(this.readyState == 4 && this.status == 200) {
            result.innerHTML = this.responseText;
          } else {
            result.innerHTML = "...";
          }
        }
        req.open('POST', '/xmlhttp', true);
        req.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
        req.send("name=" + document.getElementById('name').value);
      }
    </script>
  </head>
  <body>
    <form action="index" method="post">
      <label>Name:<input type="text" id="name" value="" /></label>
      <button type="button" id="btn-post" onclick="do_ajax();">Click</button>
      <div id="result"></div>
    </form>
  </body>
</html>
@app.route('/xmlhttp', methods=['GET', 'POST'])
def xmlhttp():
    if request.method == 'POST':
        name = request.form['name']
        return 'hello' + name
    return render_template('XMLHttpRequest.html')

WebSocket(Flask-Socketio)

<!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="//cdn.bootcss.com/socket.io/1.5.1/socket.io.min.js"></script>
    <script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        var socket = io.connect();

        socket.on('connect', function() {
            socket.emit('connect_event', {data: 'connected!'});
        })

        socket.on('server_response', function(msg) {
            $('#log').append('<br>' + $('<div/>').text('Received #' + ': ' + msg.data).html());
        });

        $('form#emit').submit(function(event) {
                socket.emit('client_event', {data: $('#emit_data').val()});
                return false;
            });
    });

    </script>
</head>
<body>
    <h2>WebSokect</h2>
    <form id="emit" method="POST" action='#'>
        <input type="text" name="emit_data" id="emit_data" placeholder="Message">
        <input type="submit" value="Echo">
    </form>
    <div id='log'></div>
</body>
</html>
#!/usr/bin/env python
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config.from_pyfile('config.py')

socketio = SocketIO(app)


@app.route('/')
def index():
    return render_template('websocket.html')


@socketio.on('client_event')
def client_msg(msg):
    emit('server_response', {'data': msg['data']})


@socketio.on('connect_event')
def connected_msg(msg):
    emit('server_response', {'data': msg['data']})


if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0')

参考

源码