【问题标题】:Passing json data from jquery to flask [duplicate]将json数据从jquery传递到flask [重复]
【发布时间】:2017-10-02 20:11:14
【问题描述】:

我想将一些 Json 数据从 jQuery 传递到烧瓶。我有一个添加用户方法,它采用一些表单值并将它们传递给烧瓶。

function kullaniciEkle(event) // add a user
{
    event.preventDefault();

    var hataSayisi = 0;

    $('#addUser input').each(function (index, val) {
        if ($(this).val() === '') {
            hataSayisi++;
        }
    });

    console.log("Number of errors: ", hataSayisi);

    if (hataSayisi === 0) {

        var yeniKullanici = {
            'kullanıcıAdı' : $('#kullaniciEkle fieldset input#girisIsim').val(),
            'eposta' : $('#kullaniciEkle fieldset input#girisEposta').val(),
            'tamİsim' : $('#kullaniciEkle fieldset input#girisTamIsim').val(),
            'yaş': $('#kullaniciEkle fieldset input#girisYas').val(),
            'yer' : $('#kullaniciEkle fieldset input#girisSehir').val(),
            'cinsiyet' : $('#kullaniciEkle fieldset input#girisCinsiyet').val()
        }

        console.log(yeniKullanici);
        console.log(JSON.stringify(yeniKullanici));

        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(yeniKullanici),
            url: '/add',
            success: function(data){
                console.log("Are we here?");
                $('#kullaniciEkle fieldset input').val('');


            },
            error: function(xhr, textStatus, error){
                alert(xhr.responseText);
            },
            dataType: "json"
        });

    } else {
        alert("Please fill in all form fields");
    }

}

而flask中的add方法也是这样的。

@app.route('/add', methods=['POST'])
def addUser():
    if request.method == "POST":
        content = request.get_json(silent=True)
        print (content)
        return 'Hi there'

看起来我可以从烧瓶中获取 json 数据。但在 jQuery 方面,我想错误部分已执行。因为如果 addUser() 函数返回此值或者如果返回值为空则返回空警报消息,我会收到一条警报消息“您好”。

【问题讨论】:

    标签: javascript jquery python json flask


    【解决方案1】:

    ajax 调用中的dataType 参数告诉jQuery 期望从服务器返回什么类型。您已指定 json,但您没有从 Flask 处理程序返回 JSON,因此 jQuery 会引发错误。

    要么实际返回 JSON,要么删除该参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      相关资源
      最近更新 更多