在javascript确认后调用php函数

时间:2014-04-16 14:11:27

标签: javascript php

我想在JavaScript确认后调用函数deleteUser()。这是我的代码。请帮帮我。

<?php
session_start();
include_once("DataSourceController.php");
$DeletedBy = $_SESSION['ID'];
$Name = $_GET['uname'];
echo '
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
deleteUser();
}
</script>';
function deleteUser(){
$sql_DeleteUser="UPDATE login
            SET Deleted=1,DeletedAt= now(),DeletedBy=".$DeletedBy."
            Where User='".$Name."';";
mysql_query($sql_DeleteUser);
echo'
        <script type="text/javascript">                     
        alert("User '.$Name.' Successfully deleted."); 
        window.location.href = "../pages/DeleteUser.php";
        </script>'; 
}
?>

3 个答案:

答案 0 :(得分:3)

你的初步问题中有一些错误的理论。尽管JavaScript是一种客户端语言,但PHP却不是。您将使用当前代码获得未定义的函数错误,因为它未在javascript中定义。

为了让JavaScript执行PHP函数,强烈建议学习和使用AJAX。当用户执行某个操作时,AJAX可用于动态执行PHP代码。许多网站使用它来查询数据库而无需重新加载页面。

JavaScript会向PHP页面发送请求,该页面将执行该函数。有关更深入的示例,请参阅此页面:Call PHP function from javascript

答案 1 :(得分:0)

使用此代码:

<?php
session_start();
include_once("DataSourceController.php");
$DeletedBy = $_SESSION['ID'];
$Name = $_GET['uname'];

function deleteUser(){
$sql_DeleteUser="UPDATE login
            SET Deleted=1,DeletedAt= now(),DeletedBy=".$DeletedBy."
            Where User='".$Name."';";
mysql_query($sql_DeleteUser);
echo'
        <script type="text/javascript">                     
        alert("User '.$Name.' Successfully deleted."); 
        window.location.href = "../pages/DeleteUser.php";
        </script>'; 
}

//first, we check whether the user has confirmed or not
if(!isset($_GET['confirmed'])) { //if they haven't, we display the confirmation message
    ?>
    <script type="text/javascript">
    var responce=confirm("Are you sure you want to delete this user?");
    if (!(responce==true)){
        //if confirmed, reload the page with added 'confirmed' parameter
        window.location.href="<?php echo $_SERVER['PHP_SELF'].$_SERVER['REQUEST_URI'] ?>?confirmed=1"
    }
    </script>
    <?php
}
elseif($_GET['confirmed'] == 1) {
   deleteUser();
}
?>

答案 2 :(得分:0)

你可以通过以下方式实现:

1 /通过GET(例如)发送信息重定向到php脚本同步:

<script type="text/javascript">
     var responce=confirm("Are you sure you want to delete this user?");
     if (!(responce==true)){
         window.location.href = ("myScript.php?user="+userName); //var userName should be defined before
     }
</script>';

和myScript.php:

<?php 
    if isset($_GET['user']){
       $name = $_GET['user'];
    }
    //some stuff    
    deleteUser($name); //Here you call your function     
    header('Location: myPage.php'); //You return to your first script    
?>

2 /通过调用myScript.php

的AJAX请求异步