我的ajax代码:
$.ajax({
type: 'POST',
url: URL + "xyz/" ,
data: {"email": email},
success: function(data) {
alert('hello')
},
dataType: "json",
});
我在python + bottle框架中的处理程序:
def index():
if request.POST == XMLHttpRequest:
email = request.GET.get('email')
response.COOKIES['email'] = email
if check_email(email): //a method written for checking email
return some template
else:
return False //here i want to return some error message to ajax. How to
做到了吗?以及如何在ajax中捕获错误。
抛出错误:NameError(“未定义全局名称'XMLHttpRequest'”,) 是瓶子支持吗?
答案 0 :(得分:2)
2件事。首先,我不明白为什么你要检查它是否是XMLHTTPRequest?我只是检查数据是否已通过POST发送。此外,它看起来像你通过POST发送,但试图通过GET检索。尝试:
def index():
if request.method == "POST":
email = request.POST['email']
response.COOKIES['email'] = email
if check_login(email):
return some template
else:
return False
答案 1 :(得分:0)
只需返回常规的404或500响应即可。 Web浏览器非常智能,可以了解这一点,并调用javascript代码中定义的错误回调。
对于jQuery,我认为回调是全局的,但我不确定我的jquery-fu是否很弱。
答案 2 :(得分:0)
在Python中检查“XmlHttpRequest”是没有意义的。这是一个围绕浏览器功能的Javascript包装器,而不是Python知道或关心的任何东西。
如果你真的需要检查POST是否来自Ajax,你可以检查请求标头 - 与其他JS框架一样,jQuery总是设置HTTP_X_REQUESTED_WITH
标头。事实上,有一个例子在Accessing Request data的Bottle文档中使用了那个确切的标题。