1

PHP 在 JS 之前首先执行,但是如果数据不为空,是否有一种简单的方法可以输出确认对话框(如 Javascript 确认),就像在这个条件 PHP 语句中一样:

<?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替换功能?谢谢。

4

3 回答 3

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
}
于 2013-02-11T05:54:28.920 回答
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>
于 2013-02-11T05:55:03.333 回答
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

}
于 2013-02-11T05:58:58.260 回答