Javascript停止PHP脚本
我在Javascript停止PHP脚本,javascript,php,jquery,Javascript,Php,Jquery,我在script1.php中有一个按钮删除文件 单击该按钮后,我想显示一个JSconfirm框来确认操作 我正在使用以下代码: <script language="javascript"> if (confirm("Are you sure to delete this file ?")) { // Will continue executing the script } else { window.stop(); } <
script1.php
中有一个按钮删除文件
单击该按钮后,我想显示一个JSconfirm
框来确认操作
我正在使用以下代码:
<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代码将以任何方式执行
那么,有没有办法“暂停”执行,直到单击“执行”按钮?分开前端和后端,在两者之间发送消息 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();
}
}
});
});
您确定要删除此文件吗
$(文档).ready(函数(){
$(“#对话框确认”)。对话框({
可调整大小:false,
高度:“自动”,
宽度:400,
莫代尔:是的,
按钮:{
“做它”:函数(){
$(此).dialog(“关闭”);
$.post(“post.php”,{filename:“error”})
.完成(功能(数据){
警报('Success:'+JSON.stringify(数据));
})
.fail(函数(jqXHR、textStatus、errorshown){
警报('ERROR:'+JSON.stringify(ERROR抛出));
});
},
},
取消:函数(){
$(此).dialog(“关闭”);
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);
?>
无论JavaScript中发生什么,PHP代码都将运行。在将HTML发送到客户端之前,整个页面将被完全呈现。客户端接收JavaScript并决定是否要运行它。为了让JavaScript操作在PHP中启动某些东西,必须重定向或进行AJAX调用。没有别的办法了。感觉你们对什么运行服务器端和什么运行客户端有误解。好吧,读了你们的话后,我觉得自己很愚蠢!那么就是AJAX了。除了@sjahan的观点之外,我建议大家阅读一下客户端和服务器代码之间的差异。
<?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);
?>