flask使用ajax


简单使用ajax

参考文档

<script type=text/javascript>
$(document).ready(function(){
    $('button#ajax').click(function() {
        $.ajax ({
            type : "POST",
            url : "{{ url_for('index.login') }}",
            data:JSON.stringify({
                name: $('input[name="name"]').val(),
                passwd: $('input[name="passwd"]').val()
            }),
            contentType: 'application/json;charset=UTF-8',
            success: function(result) {
                if (result.judge == true)
                {
                    window.location = '/';
                }
                else 
                {
                    $("#showerror").show();
                    $("#error").text(result.error);
                }
            }
        });
    });
});
</script>

ajax使用CSRF

参考文档

首先注册CSRF

from flask_wtf.csrf import CsrfProtect
csrf = CsrfProtect()
csrf.init_app(app)

在模板中使用

var csrftoken = "{{ csrf_token() }}"
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken)
            }
        }
    });
Author: honmaple

NO CONTENTS

lin.jiang

风落花语风落天,花落风雨花落田.