2017-10-20 102 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方法。