Javascript停止PHP脚本

时间:2018-10-31 16:19:23

标签: javascript php jquery

我在script1.php中有一个按钮删除文件

单击该按钮后,我要显示一个JS confirm框以确认操作。

我正在使用此代码:

<script language="javascript">
    if (confirm("Are you sure to delete this file ?")) {
        // Will continue executing the script
    } else {
        window.stop();
    }
</script>
<?php
// Delete the file ...
?>

这段代码可以满足我的要求:除非用户确认操作,否则php不会执行。

现在,如果我想自定义confirm box(添加另一个按钮,修改样式...),我想到使用jQuery .dialog

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="dialog-confirm" title="Do you wanna continue ?">
  <p>Are you sure to delete this file ?</p>
</div>

<script language="javascript">
$( document ).ready(function() {
  $("#dialog-confirm").dialog({
    resizable: false,
    height: "auto",
    width: 400,
    modal: true,
    buttons: {
      "Do it": function() {
        $(this).dialog("close");
      },
      Cancel: function() {
        $(this).dialog("close");
        window.stop();
      }
    }
  });
});
</script>
<?php
// Delete the file ...
?>

不幸的是,这不起作用,其余的php代码将以任何方式执行。

那么,有没有一种方法可以通过单击“执行”按钮来“暂停”执行?

1 个答案:

答案 0 :(得分:0)

前端和后端分开,在两个之间发送消息。

Javascript要求确认并获得确认-向php脚本发送请求。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="dialog-confirm" title="Do you wanna continue ?">
  <p>Are you sure to delete this file ?</p>
</div>

<script language="javascript">
$( document ).ready(function() {
  $("#dialog-confirm").dialog({
    resizable: false,
    height: "auto",
    width: 400,
    modal: true,
    buttons: {
      "Do it": function() {
        $(this).dialog("close");
        $.post( "post.php", {filename: "error"})
            .done(function( data ) {
                alert('Success: '+JSON.stringify(data));
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                alert('ERROR: '+JSON.stringify(errorThrown));
            });
  },
      },
      Cancel: function() {
        $(this).dialog("close");
        window.stop();
      }
    }
  });
});

php脚本等待文件名,处理文件操作(例如删除)并发送一些反馈。

<?php
$fn = $_POST['filename'];
//delete file with name $fn
//send result
if($result=='error') //something went wrong
{
    header('HTTP/1.1 500 Ended up with bad result');
    header('Content-Type: application/json');
    $response_array['status'] = "error"; 
    $response_array['data'] = $data;   
}else{ //everything ok
    header('Content-type: application/json');
    $response_array['status'] = 'success'; 
    $response_array['data'] = $data;
}   
echo json_encode($response_array);
?>