Language/UI

Ajax를 활용한 Popup과 Post Rest 전송

아르비스 2019. 11. 21. 18:28

web. HTML

 에서 ajxa를 이용한 Rest 호출 및 Popup

Rest API

 $.ajax({ 
        type: 'post' , 
        url: 'http://localhost:5000/send' , 
        data : { data : result.text } , 
        success: function(data) { console.log("success") 
        } });

 

popup과 같이 쓴 코드


<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>

          document.getElementById('startButton').addEventListener('click', () => {
            codeReader.decodeFromVideoDevice(selectedDeviceId, 'video', (result, err) => {
              if (result) {
                console.log(result)
                document.getElementById('result').textContent = result.text
                  /** popup  start **/

                  let flag = confirm("Barcode [ " + result.text +  " ] 서버로 데이터 전송하겠습니까?")
                  if(flag) {
                      $.ajax({
                          type: 'post' ,
                          url: 'http://localhost:5000/send' ,
                          data : { data : result.text } ,
                          success: function(data) { console.log("success")
                          } });
                  }
                  
                  /** popup  end **/
              }
              if (err && !(err instanceof ZXing.NotFoundException)) {
                console.error(err)
                document.getElementById('result').textContent = err
              }
            })
            console.log(`Started continous decode from camera with id ${selectedDeviceId}`)
          })

 

수신쪽은 Python Flask로 간단하게.

Flask Code

import sqlite3

from flask import Flask, render_template, request


app = Flask(__name__, static_folder='.', static_url_path='')
#app = Flask(__name__)
val = 0

@app.route('/')
def response_test():
    return render_template('index.html')
#    return app.send_static_file('index.html')

@app.route('/send/', methods=['POST'])
def send():
#    code = request.args.get('code')
    code = request.form['data']
    print("Barcode is : %s" % code)
    return render_template('code.html', code=code)

#@app.route('/send/<barcode>')
#def send(barcode):
#    print("Barcode is : %s" % barcode)
#    return render_template('code.html', code=barcode)
#    return "Barcode is : %s" % barcode

@app.route('/result')
def result():
    return render_template('code.html')

# @app.before_request
# def before_request():
#     g.db = connect_db()
#
# @app.teardown_request
# def teardown_request(exception):
#     db  = getattr(g, 'db', None)
#     if db is not None:
#         db.close()
#
# def connect_db():
#     return sqlite3.connect(app.config['DATABASE'])


if __name__ == '__main__':
    app.run()


 

특이하게 뭘 잘 못했는지..  static_file을 쓰면 에러가 났다..

뭘 잘 못한거지? ㅠㅠ

 

flask-test.zip
0.01MB