2017-02-10 54 views
0

如果執行查詢,我已經向AJAX發送了一個數組以返回狀態。在AJAX中檢索響應文本

if(mysqli_query($dbconfig,"INSERT INTO todo(description) values('$desc')")){ 
     $response['success']="true"; 
} 
header('Content-type: application/json'); 
echo json_encode($response); 

在客戶端腳本中,我嘗試了下面的代碼,根據狀態顯示消息。

if(response.status=="success"){ 
     alertify.success("New item has been added successfully"); 
}else if(response.status=="error"){ 
     alertify.error("Error while adding the item"); 
} 

即使查詢運行正確,它也不能滿足這兩種情況。在我的控制檯日誌中,狀態顯示成功。

enter image description here

+0

那是你的對象打印你在成功處理程序中獲得什麼? – r1verside

+0

@ r1verside抱歉,我沒有得到什麼成功處理程序。我只是做了console.log(響應);其中響應是函數的參數。 –

+0

由於AJAX申請是異步的,成功處理程序是您傳遞給您的請願代碼以便在服務器響應您的請願時執行的功能。我想這是你寫'console.log(response)'的地方。如果是這樣,我在我的答案中提供的兩種解決方案中的任何一種都應該這樣做: – r1verside

回答

1

根據您所提供,你可以做兩件事情

if(response.status === 200){ 
    //handle success 
} else { 
    //handle error 
} 

或者,如果你喜歡,你可以嘗試用代碼:

var status = JSON.parse(response.responseText); 
if(status.status === "success"){ 
    //handle success 
}else{ 
    //handle error 
} 
+0

我嘗試了您提供的兩種方法。它在其他條件甚至狀態是成功的 –

+1

如果在結果行動處理程序中,你已經把console.log(響應),並且結果是你粘貼你的問題,這是沒有意義的。它必須工作。您是否嘗試使用[Chrome開發工具](https://developers.google.com/web/tools/chrome-devtools/) – r1verside

+1

@SureshPokharel在第二個選擇中出現錯誤,我在比較responseText中的對象而不是其狀態屬性 – r1verside