问题描述
在服务器端,我只是将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发出发帖请求时,控制台都会打印出包含我所需内容的字典.
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!!")
}});
推荐答案
- 如果返回正确类型的响应对象,则会直接从视图中返回.
- 如果是字符串,则会使用该数据和默认参数创建一个响应对象.
- 如果返回一个元组,则该元组中的项目可以提供额外的信息.这样的元组必须采用
(response, status, headers)
或(response, headers)
的形式,其中至少一项必须位于元组中.status
值将覆盖状态代码,并且headers
可以是其他标头值的列表或字典. - 如果这些都不起作用,Flask将假定返回值是有效的WSGI应用程序,并将其转换为响应对象.
- If a response object of the correct type is returned it's directly returned from the view.
- If it's a string, a response object is created with that data and the default parameters.
- 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. Thestatus
value will override the status code andheaders
can be a list or dictionary of additional header values. - 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调用返回成功状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!