开发者

how to return message to ajax?

开发者 https://www.devze.com 2023-01-27 21:46 出处:网络
my ajax code: $.ajax({ type: \'POST\', url: URL + \"xyz/\" , data: {\"email\": ema开发者_如何学编程il},

my ajax code:

$.ajax({
        type: 'POST',
  url: URL + "xyz/" ,
  data: {"email": ema开发者_如何学编程il},
  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?


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:

def index():
    if request.method == "POST":
        email = request.POST['email']
        response.COOKIES['email'] = email
        if check_login(email):
     return some template
        else:
            return False


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消