Py学习  »  Jquery

我想将jQuery、AJAX和Flask结合起来,但是我无法从服务器获得要在模板上编写的响应

Peter • 4 年前 • 1164 次点击  

我成功地将“add”按钮链接到AJAX请求,每次单击它时,我都能在控制台输出中看到它(有正确的信息),但我一生都无法想出如何从服务器返回所有必要的数据并将其写入模板。

routes.py路径

@app.route('/create_family', methods = ['GET','POST'])
def create_family():
    prefill = {'created_by':current_user.id}
    form = CreateFamily(data = prefill)
    # This if block handles the client search
    if form.validate_on_submit():
        clients = Client.query
        if form.first_name.data:
            clients = clients.filter(Client.first_name.like('%{}%'.format(form.first_name.data)))
        if form.last_name.data:
            clients = clients.filter(Client.last_name.like('%{}%'.format(form.last_name.data)))
        return render_template('create_family.html', form = form, clients = clients.all())
    # Logic for the AJAX 'GET' request
    elif request.method == 'GET':
        if request.args.get('clientID'):
            clientid = request.args.get('clientID')

            # Queries DB for client information
            client = Client.query.filter(Client.id == clientid).first()

            # HTML to insert to the family table in the form
            row = '<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>'.format(client.id,client.first_name,client.last_name,client.gen.gender,client.dob.strftime('%m-%d-%Y'))

            # I'm not sure if this is right, or how I should change it
            return jsonify(result=row)
    else:
        return render_template('create_family.html', form = form)
return render_template('create_family.html', form = form)

创建_family.html

<html>
    <head>
      <link rel="stylesheet" href="{{ url_for('static', filename = 'styles/main.css') }}">
      <script src="{{url_for('static', filename='javascriptfile.js')}}"></script>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
<body>

<!-- I omitted some of the template for brevity -->

<!-- This is the table I want to add to-->
<table class="familyView">
        <tr class="familyHeader">
            <th>Client ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Gender</th>
            <th>Date of Birth</th>
        </tr>
    </table>


<!-- I omitted some of the template for brevity -->

<!-- This is the table I want to add to-->
<form action="" method="post"><br>
{% if clients %}
    <table class="clientView">
    <tr>
        <th>Client ID</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Gender</th>
        <th>Date of Birth</th>
    </tr>
    {% for c in clients %}
    <tr>
        <td class="clientID">{{ c.id }}</td>
        <td>{{ c.first_name }}</td>
        <td>{{ c.last_name }}</td>
        <td>{{ c.gen.gender }}</td>
        <td>{{ c.dob.strftime('%m-%d-%Y') }}</td>
        <td><button class="addBtn" type ="button">Add</button></td>
    </tr>
    {% endfor%}
</table>
</form>
{% endif %}

javascriptfile.js

window.onload=function(){

$(".addBtn").click(function() {
    var $recordToAdd = jQuery(this).closest('tr').find('.clientID').text();
    console.log("clientid: " + $recordToAdd);

    $.ajax({
        cache: false,
        url: 'create_family',
        type: 'GET',
        data: {'clientID': $recordToAdd,},
        success: function(response) {
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
    })
});

}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56792
 
1164 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Peter
Reply   •   1 楼
Peter    4 年前

这里有几个问题。首先也是最重要的,当我刷新页面时,我没有刷新javascript。通过硬复位(Shift+F5),我能够找出其他一些问题。

其次,当我试图从页面底部而不是顶部的表中追加一行时,我试图使用不必要的ajax请求。这一步只需jQuery就可以完成

$(document).on("click", ".addBtn", function() {
        var tr = $(this).closest('tr').clone();
        tr.find("input").attr("class", "rmBtn");
        tr.find("input").attr("value", "Remove from Family");
        $(".familyView").append(tr);
    });

第三,我不得不重写 routes.py

@app.route('/create_family', methods = ['GET','POST'])
def create_family():
    prefill = {'created_by':current_user.id}
    form = CreateFamily(data = prefill)
    if (request.method == 'GET') and request.args.get('client_ids'):
        ids = request.args.get('client_ids').split(',')
        print('ids: {}'.format(ids), file = sys.stderr)
        program = request.args.get('program')
        if len(ids) != 0:
            new_family = Family(program_id = program, 
                                created_date = datetime.utcnow(), 
                                created_by = current_user.id)
            db.session.add(new_family)
            db.session.flush()
            fam_id = new_family.id
            for cid in ids:
                new_mem = FamilyMember(family_id = fam_id, client_id = cid)
                db.session.add(new_mem)
            data = {'message': 'Family {} created at {}'.format(fam_id, new_family.created_date), 'code':'SUCCESS'}
            db.session.commit()
            return make_response(jsonify(data), 201)
        elif len(ids) == 0:
            print('this is an error', file = sys.stderr)
            data = {'message': 'Cannot create a family with no members', 'code':'ERROR'}
            return make_response(jsonify(data), 401)
    return render_template('create_family.html', form = form, client = client)

我知道这并不是我解决问题的最好解释,但现在我离最初的问题还有几天的时间,我记不清到底是什么给了我最大的麻烦。