本文介绍了Flask,如何返回 ajax 调用的成功状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在服务器端,我只是将 json-as-dictionary 打印到控制台

On the server-side, I am just printing out the json-as-dictionary to the console

@app.route('/',methods=['GET','POST'])
@login_required
def index():
    if request.method == "POST":
        print request.json.keys()
    return "hello world"

现在,每当我通过 ajax 发出 post 请求时,控制台都会打印出包含我需要的内容的字典.

Now, whenever I make a post request via ajax, the console prints out the dictionary with the contents I need.

在客户端,我一直在尝试使用各种方法基于成功的ajax调用来执行一些jquery.我刚刚意识到这可能是我的服务器端的错误,即我没有发送任何请求标头来告诉 jquery 它的 ajax 调用成功了.

On the client-side, I have been trying to use various methods to execute some jquery based on a successfull ajax call. I just realized that this might be an error on my server-side, i.e I am not sending any request header to tell jquery that its ajax call was a success.

那么我如何向我的客户发送 OK 状态以告诉它一切正常?

So how do I send an OK status back to my client to tell it everything is all right?

为了完整起见,这是我的客户端代码

For the sake of completeness, here is my clientside code

$.ajax({
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(myData),
    dataType: 'json',
    url: '/',
    success: function () {
        console.log("This is never getting printed!!")
    }});

推荐答案

关于Flask 中的响应:

视图函数的返回值会自动转换为响应对象.如果返回值是一个字符串,它会被转换为一个响应对象,该字符串作为响应主体、一个 200 OK 状态代码和一个 text/html mimetype.Flask 将返回值转化为响应对象的逻辑如下:

  1. 如果返回了正确类型的响应对象,它将直接从视图中返回.
  2. 如果是字符串,则使用该数据和默认参数创建响应对象.
  3. 如果返回一个元组,元组中的项目可以提供额外的信息.此类元组必须采用 (response, status, headers)(response, headers) 形式,其中元组中必须至少包含一项.status 值将覆盖状态代码,headers 可以是附加标题值的列表或字典.
  4. 如果这些都不起作用,Flask 将假定返回值是有效的 WSGI 应用程序并将其转换为响应对象.
  1. If a response object of the correct type is returned it's directly returned from the view.
  2. If it's a string, a response object is created with that data and the default parameters.
  3. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status, headers) or (response, headers) where at least one item has to be in the tuple. The status value will override the status code and headers can be a list or dictionary of additional header values.
  4. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object.

因此,如果您返回文本字符串(正如您所做的那样),您的 AJAX 调用必须接收的状态代码是 200 OK,并且您的成功回调必须正在执行.但是,我建议您返回 JSON 格式的响应,例如:

So, if you return text string (as you are doing), the status code that your AJAX call has to receive is 200 OK, and your success callback must be executing. However, I recommend you to return a JSON formatted response like:

return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

这篇关于Flask,如何返回 ajax 调用的成功状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:19