PHP首先在JS之前执行,但如果数据不是空的,就像在这个条件PHP语句中一样,有一种简单的方法可以输出确认对话框(如Javascript确认):
<?php
if (!empty($data)) {
//data is not empty
//Ideally I want to show a confirmation dialog in this part to the user
//to confirm if the user wants to overwrite the existing data
//If the user confirms
//Overwrite the existing data here
} else {
//data is empty,proceed to other task
//don't show any dialog
}
我不想向用户添加另一个表单,只是像JS确认的简单确认对话框。或者是否有PHP替换函数?感谢。
答案 0 :(得分:3)
我喜欢将数据和代码分开,所以我喜欢从PHP
创建一个JS变量// I always use json_encode when creating JS variables from PHP to avoid
// encoding issues with new lines and quotes.
var isDataEmpty = <?php echo json_encode(empty($data)); ?>;
if (!isDataEmpty) {
if (confirm("Some message")) {
overwriteExistingData();
}
} else {
// proceed
}
答案 1 :(得分:0)
您可以让您的PHP代码编写如下代码的JavaScript:
<script type="JavaScript">
$(document).ready(function(){
<?php
if (!empty($data)) {
?>
var answer = confirm("Are you sure you want to overwrite?");
<?php
} else {
?>
// Data is empty
<?php
}
?>
});
</script>
答案 2 :(得分:0)
请参阅以下代码
<?php
if (!empty($data)) {
echo '<script language="javascript" type="text/javascript">window.confirm("data is not empty")</script>';
//data is not empty
//Ideally I want to show a confirmation dialog in this part to the user
//to confirm if the user wants to overwrite the existing data
//If the user confirms
//Overwrite the existing data here
} else {
echo '<script language="javascript" type="text/javascript">window.confirm("data is empty here")</script>';
//data is empty,proceed to other task
//don't show any dialog
}