如何向ajax返回消息?
我的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'未定义”,) 瓶子有支撑吗?
my ajax code:
$.ajax({
type: 'POST',
url: URL + "xyz/" ,
data: {"email": email},
success: function(data) {
alert('hello')
},
dataType: "json",
});
my handler in python + bottle framework:
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
do it? And How to caught the error in ajax.
throwing error: NameError("global name 'XMLHttpRequest' is not defined",)
is bottle support it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
2件事。首先,我不明白你为什么要检查它是否是 XMLHTTPRequest?我只是检查数据是否已通过 POST 发送。另外,您似乎正在通过 POST 发送,但尝试通过 GET 检索。尝试:
2 things. First, I don't see why you're trying to check to see if it's an XMLHTTPRequest? I would just check to see if data has been sent via POST. Also it looks like you're sending through POST but trying to retrieve through GET. Try:
只需返回常规 404 或 500 响应即可。 Web 浏览器足够聪明,可以了解这一点,并调用 javascript 代码中定义的错误回调。
对于 jQuery,我相信回调是全局的,但我不确定,因为我的 jquery-fu 很弱。
Just return a regular 404 or 500 response. The web browser is smart enough to know about that, and calls the error callback defined in the javascript code.
For jQuery, I believe the callback is global, but I'm not sure as my jquery-fu is weak.
在 Python 中检查“XmlHttpRequest”是没有意义的。这是一个围绕浏览器功能的 Javascript 包装器,而不是 Python 知道或关心的任何东西。
如果您确实需要检查 POST 是否来自 Ajax,则可以检查请求标头 - jQuery 与其他 JS 框架一样,始终设置
HTTP_X_REQUESTED_WITH
标头。事实上,有一个示例使用 Bottle 文档中的确切标头 访问请求数据。It doesn't make sense to check "XmlHttpRequest" in Python. That's a Javascript wrapper around a piece of browser functionality, not anything that Python knows or cares about.
If you really need to check that the POST is coming from Ajax, you can check the request headers - jQuery, like other JS frameworks, always sets a
HTTP_X_REQUESTED_WITH
header. And, in fact, there's an example that uses that exact header on the Bottle documentation for Accessing Request data.