gpt4 book ai didi

jquery - Flask,如何为ajax调用返回成功状态码

转载 作者:IT老高 更新时间:2023-10-28 21:33:14 24 4
gpt4 key购买 nike

在服务器端,我只是将 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。我刚刚意识到这可能是我的服务器端的错误,即我没有发送任何请求 header 来告诉 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在 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, a 200 OK status 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) 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 格式的响应,例如:

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

关于jquery - Flask,如何为ajax调用返回成功状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com