jquery – Flask,如何返回ajax调用的成功状态代码

前端之家收集整理的这篇文章主要介绍了jquery – Flask,如何返回ajax调用的成功状态代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在服务器端,我只是将json-as-dictionary打印到控制台
@app.route('/',methods=['GET','POST'])
@login_required
def index():
    if request.method == "POST":
        print request.json.keys()
    return "hello world"

现在,每当我通过ajax发布一个发布请求时,控制台都会输出我需要的内容的字典.

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

那么如何将OK状态发回给我的客户来告诉它一切都好吗?

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

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

解决方法

About Responses in Flask:

About Responses

The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body,an 200 OK error code and a text/html mimetype. The logic that Flask applies to converting return values into response objects is as follows:

  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) 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格式的响应,如:

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

猜你在找的jQuery相关文章