检查PHP中是否使用AJAX显示警告框

时间:2017-03-12 10:32:14

标签: javascript php jquery ajax alert

我使用AJAX将数据发送到PHP文件,并根据发送的数据显示alert()或显示。

在AJAX中的success函数内,如何检测是否显示了警告框?

var called = $("#called").val();

$.ajax({
   type: "POST",
   url: "send.php",
   data: "name=" + called,,
   success: function(data) {
      if(alert box was shown) {
         // something happens
      }else{
         // alert box wasn't shown, something else happens.  
      }  
   }               
});

send.php

<?php
if($_POST['name'] == 'john') {
   echo'
   <script>
   alert("Correct name");
   </script>
   ';
}

3 个答案:

答案 0 :(得分:3)

最好从ajax请求发回结果,并在success回调中显示/不显示提醒:

$.ajax({
   type: "POST",
   url: "send.php",
   data: "name=" + called,,
   success: function(data) {    
      if ( data == "show" ) {
         // something happens
         alert("Correct name");
      } else {
         // alert box wasn't shown, something else happens.  
      }  
   }               
});

在您的服务器上:

if ( $_POST['name'] == 'john' ) {
   echo "show";
}

答案 1 :(得分:0)

您可以使用json_encode() php函数从php返回数据。

这将是一个更好的方法:

PHP:

if (!isset($_POST['name'] || empty($_POST['name']) {
    die(json_encode(array('return' => false, 'error' => "Name was not set or is empty")));
} elseif ($_POST['name'] == "John") {
    die(json_encode(array('return' => true)));
} else {
    die(json_encode(array('return' => false, 'error' => "Name is different than John.")));
}

此时,您将被允许检查JS返回的值,并决定是否需要显示成功警报或向控制台发送错误消息(或执行您想要的操作......)。

JS:

var called = $("#called").val();

$.ajax({
   type: "POST",
   url: "send.php",
   dataType: "JSON", // set the type of returned data to json
   data: {name: called}, // use more readable syntaxe
   success: function(data) {
      if (data.return) { // access the json data object 
         alert("Congrats ! Your name is John !");
      } else {
         console.log("Sorry, something went wrong : " + data.error);  
      }  
   }               
});

因此,json_encode()允许从JS返回易于访问的对象,并且还允许您在返回为false时轻松设置和显示错误消息。

希望它有所帮助!

答案 2 :(得分:0)

PHP不知道是否显示了警报,因为在javascript中,alert()函数没有返回值,也没有可用于向服务器发送ajax请求点击确认的事件。

一种解决方案是在$ .ajax()的成功事件中使用confirm()命令,如果用户单击“确定”或“取消”,则会发送另一个ajax请求。

像这样的东西

var called = $("#called").val();

$.ajax({
   type: "POST",
   url: "send.php",
   data: "name=" + called,
   success: function(data) {

        if (data == "show") {

            var clicked = confirm("Correct name");

            if (clicked == true || clicked == false) {
                $.ajax({
                    url: "send.php?clicked=1",
                });
            }  
        }
        else {
             // Whatever to do than...
        } 
    }
});