【问题标题】:how to use jsonp with jsonify in python and catch the return of the ajax如何在python中使用jsonp和jsonify并捕获ajax的返回
【发布时间】:2018-11-23 10:42:06
【问题描述】:

我想使用 jsonp 调用带有 ajax 的函数(因为我调用 url 的服务器与我发送 ajax 的服务器不同)。 ajax 调用一个 python 函数来删除一些目录,然后返回一些东西(返回对我来说并不重要)。当它返回时,它不会在成功函数中返回(它在错误函数中返回)。我做错了什么?

P.S:我正在使用 python 和烧瓶中的 jsonify

AJAX:

$.ajax({
    url: 'http://serverPath:1234/deleteDir?path='+ id,
    type: 'GET',
    dataType: 'jsonp',
    success: function (data) { console.log(data);},//console.log(data); },
    error: function (data) { console.log(data); },
});

服务器上的 Python 函数:

@app.route("/deleteDir", methods=['POST', 'GET'])

def deleteDir():
   path =request.args.get('path') 
   pathAdequacao = 'reports/'+path+'/adequacao'
   pathBrain = 'reports/'+path+'/brain'

   try:

      shutil.rmtree(pathAdequacao, ignore_errors=True)
   except:
      pass

   try:
      shutil.rmtree(pathBrain, ignore_errors=True)
   except: 
      pass  

   return jsonify({'response':'ok'})

发送到错误函数的返回值(状态为 200):

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

【问题讨论】:

    标签: python ajax flask jsonp


    【解决方案1】:

    您正在使用 JSONP,因此您必须将 JSONP 填充添加到结果中:

    return '{funcname}({data})'.format(
        funcname=request.args.get('callback'),
        data=jsonify({'response':'ok'}),
    )
    

    在此处阅读有关 JSONP 的更多信息:https://en.wikipedia.org/wiki/JSONP

    【讨论】:

      猜你喜欢
      • 2016-01-30
      • 1970-01-01
      • 2021-12-26
      • 2013-10-30
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2012-09-11
      相关资源
      最近更新 更多