2010-11-30 51 views
1

我的Ajax代码:如何将消息返回给ajax?

$.ajax({ 
     type: 'POST', 
    url: URL + "xyz/" , 
    data: {"email": email}, 
    success: function(data) { 
    alert('hello') 
    }, 
    dataType: "json", 
    }); 

我在Python +一瓶架构处理器:

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

你是从哪里复制的?大多数Pythons行没有任何意义... – 2010-11-30 20:43:15

回答

0

只需返回一个正常的404或500响应。 Web浏览器足够聪明,可以知道这一点,并调用JavaScript代码中定义的错误回调。

对于jQuery,我认为回调是全球性的,但我不确定我的jquery-fu是否软弱。

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 
0

在Python中检查“XmlHttpRequest”没有意义。这是一个浏览器功能的Javascript包装,而不是Python知道或关心的任何东西。

如果您确实需要检查POST是否来自Ajax,则可以检查请求标头 - 与其他JS框架一样,jQuery始终设置HTTP_X_REQUESTED_WITH标头。事实上,有一个例子在Bottle文档中使用了这个确切的头文件,用于Accessing Request data