【问题标题】:HTTP response webapp2 to AJAX callbackHTTP 响应 webapp2 到 AJAX 回调
【发布时间】:2014-10-20 11:03:35
【问题描述】:

如何使用 webapp2 向 AJAX 回调发送错误响应?

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

我在 post 方法上旋转我的轮子。这就是我所在的位置。

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))

响应是在标题中还是在正文中?什么是正确的格式以便回调拾取它?

【问题讨论】:

  • 也许我试图滥用 AJAX 错误回调。在 AJAX 帖子中,我成功地将数据发送到服务器。我想要做的是使用错误回调来传达服务器端验证错误。我现在发现我可以通过成功回调将其传回。通过成功回调发送服务器验证错误似乎很奇怪。其他人是怎么做到的?

标签: jquery python ajax webapp2


【解决方案1】:

如果要使用jQuery ajax请求的错误回调,则需要将响应http代码改成代表错误的,例如Internal Server Error为500,例如:

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

那么你需要为你的班级定义一个handle_exception,例如:

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

然后将调用您在 javascript 代码中的错误回调。

按照你的做法,你应该使用成功回调而不是错误回调,例如:

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

两种方式都可以,取决于你使用哪一种方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多