2017-10-20 94 views
0

我是編程新手,對Ajax並不擅長。
我想從Ajax中的php腳本獲取值。
我發送一個JavaScript變量的PHP腳本這樣的:來自Ajax的返回值

$('#deleteSelectedButton').on('click', function() { 
    if (confirm('Do you want to suppress the messages ?')) { 
     $.ajax({ 
      type: 'POST', 
      url: 'suppression-message', 
      data: { 
       'checkboxIdArray': checkboxIdArray.toString(), 
      } 
     }); 
     return false; 
    } 
}); 

這被髮送到以下PHP腳本,其根據包含在所述checkboxIdArray的ID刪除消息:

我想要將$ message變量返回給我的javascript,以便根據腳本的結果顯示一條消息。

我真的很感謝一些幫助...
謝謝。

+0

你可以從php中'echo'變量,並在'success:function(resp)'ajax回調函數中獲取它 – Lixus

+0

所以使用成功處理程序。閱讀jQuery的文檔。 – epascarello

回答

0

你必須使用功能的成功,實際上在消息中包含的響應

$.ajax({ 
      type: 'POST', 
      url: 'suppression-message', 
      data: { 
       'checkboxIdArray': checkboxIdArray.toString(), 
      }, 
      success : function(response){ 
       // your code or logic 
       alert(response); 
      } 
     }); 

PHP

if ($deleteSuccess === true) { 
    $message = 'Success'; 
} else { 
    $message= "Error"; 
} 
echo $message; 
0
$('#deleteSelectedButton').on('click', function() { 
    if (confirm('Do you want to suppress the messages ?')) { 
     $.ajax({ 
      type: 'POST', 
      url: 'suppression-message', 
      data: { 
       'checkboxIdArray': checkboxIdArray.toString(), 
      }, 
      success: function(response){ 
       alert(response); 
      } 
     }); 
     return false; 
    } 
}); 
0

沒有什麼特別之處用JavaScript做一個HTTP請求。

您可以像使用其他任何HTTP響應一樣從PHP輸出響應中的數據。

echo $message; 

在JavaScript中,你處理它as described in the documentation for jQuery.ajax

編寫一個接受響應內容作爲第一個參數的函數。

然後在jqXHR對象上調用done .ajax返回並傳遞該函數。

function handleResponse(data) { 
     alert(data); 
    } 

    var jqXHR = $.ajax({ 
     type: 'POST', 
     url: 'suppression-message', 
     data: { 
      'checkboxIdArray': checkboxIdArray.toString(), 
     } 
    }); 

    jqXHR.done(handleResponse); 
0

嘗試一下代碼AJAX

<script> 
$('#deleteSelectedButton').on('click', function() { 
    if (confirm('Do you want to suppress the messages ?')) { 
     $.ajax({ 
      type: 'POST', 
      url: 'suppression-message', 
      data: { 
       'checkboxIdArray': checkboxIdArray.toString(), 
      } 
     }).done(function(result) 
     { 
      alert(result); 
     }); 
     return false; 
    } 
}); 

</script> 

這裏獲得的價值是PHP代碼

<?php 
if (isset($_POST['checkboxIdArray'])) { 

    $checkboxIdArray = $_POST['checkboxIdArray']; 
    $str = json_encode($checkboxIdArray); 
    $tab = explode(",", $str); 
    $deleteSuccess = true; 

    foreach($tab as $id) 
    { 
     $id = filter_var($id, FILTER_SANITIZE_NUMBER_INT); 
     if (!$messageModelDb->delete($id)) { 
      $deleteSuccess = false; 
      die(); 
     } 
    } 
    if ($deleteSuccess === true) { 
     $message = 'Success';; 
    } else { 
     $message= "Error"; 
    } 
    echo $message; 
} 
?> 
0

因爲jQuery的實施deferreds,.done是實現成功的首選方式回電話。您還應該使用失敗響應代碼實施.fail方法。