Javascript停止PHP脚本[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我在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代码将以任何方式执行。

那么,有没有办法“停止”执行直到点击“执行”按钮?

javascript php jquery
1个回答
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);
?>
© www.soinside.com 2019 - 2024. All rights reserved.