簡體   English   中英

HTTP響應webapp2對AJAX回調

[英]HTTP response webapp2 to AJAX callback

如何使用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))

響應是在標題中還是在正文中? 什么是正確的格式,以便回調程序可以接收它?

如果要使用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);
        }
    }
});

兩種方法都應該起作用,取決於您使用哪種方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM