2011-09-16 129 views
6

我有一個帖子函數沒有被錯誤捕獲。jquery Ajax post成功/錯誤函數

這是從postride.php返回的值。

if ($group_id==0) { 
echo 'No group selected'; 
return false; 
exit; 
} 

這裏是jQuery代碼:

$(document).ready(function(){ 
$('#postride').submit(function(event) { 
    event.preventDefault(); 
    dataString = $("#postride").serialize(); 
    $.ajax({ 
     type: "post", 
     url: "postride.php", 
     data:dataString, 
     error: function(returnval) { 
      $(".message").text(returnval + " failure"); 
      $(".message").fadeIn("slow"); 
      $(".message").delay(2000).fadeOut(1000); 
     }, 
     success: function (returnval) { 
      $(".message").text(returnval + " success"); 
      $(".message").fadeIn("slow"); 
      $(".message").delay(2000).fadeOut(1000);  
      //setTimeout(function() { top.location.href="view.php" }, 3000); 
     } 
    }) 
    return false; 
}); 

});

post函數返回false,但錯誤函數不會觸發,只有成功函數。它將發佈「無組選擇成功」。

感謝您的幫助!

回答

21

jQuery ajax方法中的錯誤選項是由於錯誤的連接,超時,無效的url,這種性質的事情造成的錯誤。這不是你想的那種錯誤。

大多數人做的是這樣的事情...

PHP

if ($group_id == 0) { 
echo json_encode(array(
    'status' => 'error', 
    'message'=> 'error message' 
)); 
} 
else 
{ 
echo json_encode(array(
    'status' => 'success', 
    'message'=> 'success message' 
)); 
} 

的JavaScript

$(document).ready(function(){ 
$('#postride').submit(function(event) { 
    event.preventDefault(); 
    dataString = $("#postride").serialize(); 
    $.ajax({ 
     type: "post", 
     url: "postride.php", 
     dataType:"json", 
     data: dataString, 
     success: function (response) { 
      if(response.status === "success") { 
       // do something with response.message or whatever other data on success 
      } else if(response.status === "error") { 
       // do something with response.message or whatever other data on error 
      } 
     } 
    }) 
    return false; 
}); 
+0

謝謝你這麼多的澄清! – Matt

+0

不客氣Matt –

+0

不錯,@AnthonyJack!但我認爲你的意思'dataType:'json''在javascript代碼中... – Simon

0

jQuery的ajax函數的error方法只會在請求的頁面返回錯誤狀態碼時纔會被調用。你的例子可能會返回HTTP 200,這就是爲什麼success被調用; jQuery不詢問響應的內容以確定它是否成功。

$group_id爲0時,您應該設置4xx status code,方法是將echo呼叫替換爲header的呼叫。

2

wsanville是正確的: 「成功」 或 「失敗」指的是ajax請求的成功/失敗。

雖然,我發現在json響應中返回信息非常有用。因此,例如,我會postride.php像這樣迴應:

$error = false; 
if ($group_id==0) { 
    $error = 'No group selected'; 
} 
$response = array('error'=>$error); 
echo json_encode($response); 

然後在JS的「成功」的回調,我這樣做:

success: function (returnval) { 
    if (returnval.error) { 
     $(".message").text(returnval + " failure") 
     .fadeIn("slow",function(){ 
      $(this).delay(2000).fadeOut(1000); 
     }); 
    } else { 
     //do whatever user should see for succcess 
    } 
+0

安東尼傑克幾乎貼出了我要說的第一件事 - 如果你提出了我的答案,你應該加倍努力,接受他而不是我的。 –