2017-10-21 157 views
0

我在使用Ajax調用php腳本時遇到了一些問題。 我有一個指向壓制腳本的ajax。
這裏是我的JS:ajax調用後處理php錯誤

$('.js-delete-link').click(function (e) { 
    e.preventDefault(); 
    let id = $(this).closest('tr').find('.id').text(); 
    if (confirm('Voulez-vous vraiment supprimer le message ?')) { 
     let href = $(e.currentTarget).attr('href'); 
     $.ajax({ 
      url:href, 
      type:'post', 
      success:function(data){ 
       let msgJson = JSON.parse(data);     
       bootstrapNotify(msgJson.msg,msgJson.type); 
      }, 
     }) 
    } 
}); 

,這裏是我的PHP腳本在那裏我居然刪除的項目。

if ($_SERVER['REQUEST_METHOD'] === 'POST') { 

if (isset($_GET['id'])) { 

    $id = FILTER_INPUT(INPUT_GET, 'id', FILTER_VALIDATE_INT); 
    if ($id === false) { 
     $arr = array("msg" => "Id incorrect ou non spécifié", "type" => 'danger'); 
    } else { 
     if ($messageModelDb->delete($id)) { 
      $arr = array("msg" => "Le ou les messages ont été supprimés", "type" => 'success'); 
     } else { 
      $arr = array("msg" => "Le message n'existe pas !", "type" => 'danger'); 
     } 
    } 
} 

echo json_encode($arr); 

} else { 
    $_SESSION['error'] = "Vous n'êtes pas autorisé."; 
    redirect('liste-messages'); 
} 

在我的PHP我試圖抓住可能在查詢過程中出現任何錯誤,如果它發生了,我根據錯誤傳遞消息。
但是,無論我總是會得到一個成功的消息,即使該ID不存在。
對不起,如果這看起來完全明顯,但我是新來的,我有點卡在這裏!
謝謝你的幫助!

+0

服務器端重定向,而做一個Ajax調用 – charlietfl

+0

不會重定向瀏覽器頁面謝謝你,我並沒有意識到, – Simondebn

回答

1

如果isset($ _ GET [「身份證」])是假的,什麼都不會發生,因爲你應該把else語句是這樣的:

<?php 

if ($_SERVER['REQUEST_METHOD'] === 'POST') { 
    if (isset($_GET['id'])) { 

     $id = FILTER_INPUT(INPUT_GET, 'id', FILTER_VALIDATE_INT); 
     if (!$id) { 
      $arr = array("msg" => "Id incorrect ou non spécifié", "type" => 'danger'); 
     } else { 
      if ($messageModelDb->delete($id)) { 
       $arr = array("msg" => "Le ou les messages ont été supprimés", "type" => 'success'); 
      } else { 
       $arr = array("msg" => "Le message n'existe pas !", "type" => 'danger'); 
      } 
     } 
    } else { 
     $arr = array("msg" => "ID is not set", "type" => 'danger'); 
    } 
} else { 
    $arr = array("msg" => "Invalid request method", "type" => 'danger'); 
} 

echo json_encode($arr); 

然後在JavaScript文件,你可以添加一個錯誤回調:

success: function(){ 
    ... 
}, 
error: function(XMLHttpRequest, textStatus, errorThrown) { 
    alert("Status: " + textStatus + " - Error: " + errorThrown); 
} 
+0

確定這做到了,但後來我我們必須處理ajax回調中的錯誤嗎?不是在PHP腳本? – Simondebn

+0

你說得對,我已經編輯了我的anwser。 –

+0

好的非常感謝你!還有一件事,當我嘗試在我的鏈接中輸入一個錯誤的ID時,我仍然可以得到一個答案,就好像該項目存在一樣,我不明白爲什麼? – Simondebn

0

據我所知,在FILTER_INPUT可能返回NULL太多,所以$id === false會在這種情況下錯誤的。嘗試使用if(!$id)相反,如果你確定你的$ id不能爲0

+0

謝謝你! – Simondebn

+0

如果$ id = NULL,它仍然是false:http://php.net/manual/en/types.comparisons.php。我認爲最好是這樣做if!(!isset($ id)&& $ id!==「」) –

+0

@jeroene wait ...'if(!$ id)'在兩種情況下都是true,當$ id是null,當$ id爲false時,我們可以使用它來測試$ id,否? – AlexandrX