简体   繁体   中英

JSON POST on iOS with Flask

Inside my flask python web program, I save a few parameters in SessionStorage in order to send them back to flask, then save this information as a txt file.

For some reason, everything works flawlessly on PC and Android, couldn't get it to work on iOS devices. it recognizes and saves the sessionStorgae elements before sending, but no txt file is created afterwards (at the end of the app).

Client-side (HTML):

 function func() { ... $.ajax({ url: "{{ url_for('getInfo', _external=True) }}", type: 'POST', dataType: 'json', contentType: 'application/json;charset=UTF-8', success: function (response) { console.log(response); }, accepts: { json: 'application/json', }, data: JSON.stringify(log) }); return; ... } 
  <form id = "myForm" name ="myForm" method="post" action="{{url_for('final')}}" onsubmit="return func()"> 

Server-side (Flask):

@app.route("/get_info",methods = ['POST'])
def getInfo():
    list = request.get_json()
    global id
    with open(id + '.txt', 'w+') as outfile:
            json.dump(list,outfile,indent=2)
    return 'OK'

I can't figure out the solution. Also I can't remember if it used to work or not on iOS. trying to run all kinds of tests as I'm writing this. Any help would be much appreciated. Thanks.

If you believe more information is needed, I elaborated in the comments about the overall structure of that HTML page and web program.

Your code in 'DEBUG' mode

@app.route("/get_info",methods = ['POST'])
def getInfo():
    list = request.get_json()
    global id
    file_name = '{}.txt'.format(id)
    print('About to write {} to file {}'.format(str(list),file_name))
    with open(file_name, 'w+') as outfile:
            json.dump(list,outfile,indent=2)
    print('Data was written')
    return 'OK'

Found an answer for future readers: iOS puts ajax request in cache. which later on might give empty response, or don't trigger the function at all. you can solve that by adding a few parameters and headers to the ajax request, which will prevent it from happenning:

cache: false,
processData: false,
async: true,
headers: {
    "cache-control": "no-cache"
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM