FlaskとjQueryでJSONのやりとり

FlaskとjQueryでのJSONのやりとりについて。
サーバからJSONを受け取るサンプルはよく見かけるんだけど、サーバにJSONを送るものがあまりなかったので。

Flask

...
@app.route('/test', methods=['POST'])
def test():
if request.method == 'POST':
    data = request.json
    print data
    return Response('ok')
...

jQuery

$(function() {
    data = {"hoge": "fuga"};
    json = JSON.stringify(data);  // object型からJSON文字列(string型)に変換
    $.ajax({
        type: 'POST',
        url: '/test',
        data: json,
        contentType: 'application/json',
        success: function(msg) {
            console.log(msg);
        },
        error: function(msg) {
            console.log('error');
        }
    });
});

JSON.stringifyをしていなくてハマりました。


サーバ側からJSONでResponseを返す場合は$.ajaxでdataTypeを指定すること。


Flask

...
    return jsonify(res='ok')
...

jQuery

$.ajax({
    ...
    dataType: 'json',
    success: function(msg) {
        console.log(msg.res);
    },
    ...