[HTML] - search.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
        <script type=text/javascript src="{{url_for('static', filename='jQuery.js') }}"></script>
        <script>
        function test(){
                var text_data = $('#item_id').val();
                $.ajax({
                        type : 'POST',                                  <!--GET / POST-->
                        url : 'http://ip주소:5000/item_request',
                        data : {
                                item_id:text_data                       <!--key : "value"-->
                        },
                        dataType : 'JSON',
                        success : function(result){
                                alert("result = "+ result);
                                $('#a').html(result);
                        },
                        error : function(xtr,status,error){
                                alert(xtr +":"+status+":"+error);
                        }
                });
        }
        </script>
        <body>
                <p>검색하고자 하는 아이템을 입력하세요.</p>
                <input type = "text" name="item_id" id="item_id"/>
                <input type = "button" value = "데이터 요청" onclick="test()"/>
                <h1 id ="a"></h1>
        </body>
</html>
 
 

[Flask(python)] -controller.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from flask import Flask, request, Response, jsonify, render_template
 
app = Flask(__name__)
app.debug = True
 
import json
import mysql.connector
 
db = mysql.connector.connect(host="DB가 설치된 IP주소", user="DB사용자",passwd="DB비번", db='DB명', port=DB포트번호)
curs = db.cursor()
 
@app.route('/')
def index():
    return render_template('index.html')
 
@app.route('/search')
def item_search():
    return render_template('search.html')
    
@app.route('/item_request', methods =['POST'])
def item_query():
    value1 = request.form['item_id']
    item_sql = "select * from student where id ='"+value1+"'"
    curs.execute(item_sql)
    row_headers=[x[0for x in curs.description]
    rows=curs.fetchall()            
    json_data=[]                                        #list
    for result in rows:
        json_data.append(dict(zip(row_headers,result)))
    
    json_return=json.dumps(json_data[0])   #string #json
 
    return jsonify(json_return)
 
    curs.close()
 
if __name__=='__main__':
    app.run(host='0.0.0.0',port=5000)
 
db.close()
 
 

[index.html]

1
2
3
4
5
6
7
8
<!DOCTYPE html>
<html>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <body>
            <p>정보</p>
            <br><a href ="http://ip:5000/search">item search</a>
        </body>
</html>
 
 

[실행 화면]

 

+ Recent posts