社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Jquery

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

Peter • 5 年前 • 1954 次点击  

我成功地将“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
 
1954 次点击  
文章 [ 1 ]  |  最新文章 5 年前