2015-10-13 85 views
0

我有一個AJAX功能,更新我的數據庫。該功能很完善和更新數據庫後,我打電話我已經創建了successAlert()函數。但是現在我想在錯誤的情況下調用錯誤函數,但是在故意破壞代碼的情況下,我仍然得到successAlert()。阿賈克斯返回錯誤調用錯誤AJAX調用錯誤

的Ajax/JavaScript的:

var share = "test" 
var custid = "test"  

$.ajax({ 
      url: "assets/ajax/customer-rec.php", 
      type: "POST", 
      data: {UpdateAccount: "yes",custid: custid,share: share}, 
      success: function(result){ 
       successAlert()  
      }, 
      error: function(result){ 
       errorAlert()  
      } 
     }); 

PHP更新數據庫

if (isset($_POST['UpdateAccount'])){ 

    $custid = $_POST['custid']; 
    $share = $_POST['share']; 
    $query="UPDATE `users` SET `share_ord`='$share' WHERE id= $custid"; 
    $stmt = mysql_query($query); 

    if($stmt === false){ 
     return false 
    } 

} 
+0

你是如何創建一個失敗?你有沒有重新命名「assets/ajax/customer-rec.php」? –

回答

5

返回假是不是一個錯誤。如果你要發送的錯誤使用頁眉像

header('X-PHP-Response-Code: 404', true, 404); 

可以調用相同errorAlert()函數的成功也讓

$.ajax({ 
     url: "assets/ajax/customer-rec.php", 
     type: "POST", 
     data: {UpdateAccount: "yes",custid: custid,share: share}, 
     success: function(result){ 
      if(result === false){ 
       errorAlert() 
      } else { 
       successAlert() 
      }  
     }, 
     error: function(result){ 
      errorAlert()  
     } 
    }); 
+0

也值得一看http://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages – Alex

0

爲了得到錯誤,你需要返回狀態代碼「404 '從你的請求服務的PHP功能。

0

當服務器返回一個HTTP狀態代碼表示有錯誤的error回調被觸發,因此你應該送一個,前HTTP 500

if($stmt === false){ 
    header('HTTP/1.1 500 Server error'); 
} 

在這裏看到一個list of HTTP狀態碼

0

阿賈克斯()將成功的方法,因爲,一旦你的請求是由服務器成功處理然後重新運行HTTP_OK到客戶端,如果阿賈克斯沒有收到HTTP_OK,那麼它會調用錯誤調用。根據你的代碼,它會調用成功,因爲url是存在的,服務器會向瀏覽器發送HTTP_OK。 如果你想生成error:然後給錯誤的URL或斷開網絡連接或簡單地改變

在PHP:

if($stmt === false){ 
     //If you want really generate some http error. 
     header('X-PHP-Response-Code: 500', true, 500); 
     exit(0); 
     //or else continue as per code 
     // return false; 
    } 

在您的JS:

$.ajax({ 
     url: "assets/ajax/customer-rec.php", 
     type: "POST", 
     data: {UpdateAccount: "yes",custid: custid,share: share}, 
     success: function(result){ 
      if(!result){ 
       showErrorAlert() 
      } else { 
       showSuccessAlert() 
      }  
     }, 
     error: function(result){ 
      showErrorAlert()  
     } 
    });