2013-06-26 52 views
4

這是我的代碼如何jQuery中的Ajax表單提交加入錯誤處理

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#spc-comment-flag-form').submit(function() { 
     $.ajax({ 
      data: $(this).serialize(), 
      type: $(this).attr('method'), 
      url: $(this).attr('action'), 
      success: function(data) { 
       if(data['error'] == false) { 
        var msg = 'We got your flag. Our moderators will now look into it. You may close the window now!'; 
        $('#spc-comment-flag-response').html(msg); 
       } 
       else { 
        $('#spc-comment-flag-response').html(data); 
       } 
      }, 
     }); 
     return false; 
    }); 
}); 
</script> 

編輯

在服務器端的是這樣的:

@csrf_protect 
@login_required 
def flag(request, comment_id, next=None): 
    if not request.is_ajax(): 
     raise Http404 
    data = {} 
    if request.method == 'POST': 
     ... 
     data = simplejson.dumps(data) 
     return HttpResponse(data, mimetype="application/javascript") 
    else: 
     raise Http404 

我基本上服務器並且很少要寫JS。 我發送了「錯誤」:如果錯誤消息和「錯誤」錯誤,則返回true:如果服務器上沒有錯誤,則返回false!

我不知道爲什麼在上面的代碼條件邏輯不工作! 任何人都可以幫我解決它嗎?

+0

阿勒?或者它只是HTML – bipen

+0

你回送什麼樣的數據? JSON('「錯誤」:true'不是有效的JSON)?如果是這樣,你是否設置了正確的「Content-Type」響應頭?否則,jQuery將不會知道它是JSON,並且不會自動解析它。然後你必須設置dataType:'json'選項。 –

+0

發送響應爲JSON – Surya

回答

0
success: function(data) 
    { 
    if(data.error){ 
     //alert error 
    } 
    else{ 
     //alert('Success'); 
    } 
    }, 
    error: function(XMLHttpRequest, textStatus, errorThrown) 
    { 
    alert('Internal server error'); 
    //some stuff on failure 
    } 

error回調也處理錯誤,這是不是在服務器端捕獲。

+0

嘿,如果我把'mimetype'或'content_type'在服務器中不起作用 – Surya

+0

我不明白。你能詳細說明嗎?我的意思是,如果服務器端出現任何未捕獲的異常,則調用'error'回調,而不是'success'。 – Paritosh

0

如果你想處理在網頁請求錯誤您可以使用此代碼......

http://api.jquery.com/jQuery.ajax/

$.ajax({ 

}).done(function (data) { 

}).fail(function (jqXHR, textStatus) { 

}); 

以及有關在你的服務器端驗證,你可以返回錯誤使用JSON ...

+0

你在'$ .ajax裏面放了什麼?{}? –

6

試試這個...

$(document).ready(function() { 
     $('#spc-comment-flag-form').submit(function() { 
      $.ajax({ 
       data: $(this).serialize(), 
       type: $(this).attr('method'), 
       url: $(this).attr('action'), 
       success: function(data) { 
        if(data['error'] == false) { 
         var msg = 'We got your flag. Our moderators will now look into it. You may close the window now!'; 
         $('#spc-comment-flag-response').html(msg); 
        } 
        else { 
         $('#spc-comment-flag-response').html(data); 
        } 
       }, 
       error: function (data) { 
         var r = jQuery.parseJSON(data.responseText); 
         alert("Message: " + r.Message); 
         alert("StackTrace: " + r.StackTrace); 
         alert("ExceptionType: " + r.ExceptionType); 
       } 
      }); 
      return false; 
     }); 
    }); 
+0

ResponseText是否總是被定義? –

1

你必須使用你發送的JSON從服務器的響應

error: function(jqXHR jqXHR, String textStatus, String errorThrown){ 
    ... 
    ... 
} 

full documentation