gpt4 book ai didi

javascript - 将 ajax 错误从 python 返回到 jquery

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:17 25 4
gpt4 key购买 nike

我正在使用 jQuery 进行 AJAX 表单发布。但是,当我从我的 Python 服务器返回错误代码时,它被读取为成功而不是错误。我的代码如下。我是 Python 的菜鸟。如果我犯了明显的错误,请道歉。

J查询:

 $.ajax({

type:"post",
url: "/newform",
data:$('#my-form').serialize(),
success: function(msg){

alert(msg);


},
error: function(msg){

alert(msg);
}
});

Python代码:

def post(self):

email = self.get_secure_cookie("user")
id_name = self.get_argument('id1', None)

try:
credentials = Credentials(email=email, id_name=id_name)
credentials.save()

except Exception, e:
print '%s' % str(e)
msg = 'Authorization Failed. Please check if the credentials are correct'
status = "error"

else:
msg = 'Connected'
status = "success"

print 'status: %s' % status
self.write({"status": status, "msg": msg})

最佳答案

您的代码仍在返回成功的 HTTP 200 响应,但其中包含“status”:“error”。

所以你的 javascript 看起来像这样:

$.ajax({
type:"post",
url: "/newform",
data:$('#my-form').serialize(),
success: function(msg){
if (msg.status == "success") {
//handle success here
} else {
//handle error
}
},
error: function(msg){
//handle server error, such as HTTP 404, 500
}
});

关于javascript - 将 ajax 错误从 python 返回到 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26340326/

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