简体   繁体   中英

HTTP response webapp2 to AJAX callback

How do I send an error response to an AJAX callback with webapp2?

$.ajax({
    type: "POST",
    url: "/",
    data: data,
    error:function(response){
        $('#response-error').html(response);
    }
});

I'm spinning my wheels on the post method. This is where I'm at.

class PageHandler(BaseHandler):
    def post(self):
        ...
        if not valid:
            errors = "Your data stinks!"
            result = {'status': 'error', 'errors': errors}
            self.response.headers['Content-Type'] = 'application/json'
            self.response.write(json.dumps(result))

Does the response go in the header or in the body? What's the correct format so that the callback picks it up?

If you want to use the error callback of the jQuery ajax request, then you need to change the response http code to one that represents an error, for example, 500 for Internal Server Error , for example:

class PageHandler(BaseHandler):
    def post(self):
        ...
        if not valid:
            self.abort(500, "Your data stinks!")

then you will need to define a handle_exception to your class, for example:

class PageHandler(BaseHandler):
        ...
    def handle_exception(self, exception, debug):
        # here you can add eny kind of validation
        if isinstance(exception, webapp2.HTTPException):
            # Set a custom message.
            self.response.write(exception.message)
            self.response.set_status(exception.code, exception.message)
        else:
            raise # or whatever you want to do

then your error callback in the javascript code will be invoked.

The way your are doing it, you should use a success callback instead of error callback, for example:

$.ajax({
    type: "POST",
    url: "/",
    data: data,
    success:function(response){
        if(response.status==='error'){
          alert(response.errors);
        }
    }
});

both way should work, is up to you which one to use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM