php - 如何在有条件的 PHP 语句中使用 JS 确认?

标签 php javascript

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 替换函数?谢谢。

最佳答案

我喜欢将数据和代码分开,所以我喜欢从 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
}

关于php - 如何在有条件的 PHP 语句中使用 JS 确认?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14806610/

相关文章:

javascript - 语法错误: Unexpected EOF on closing &lt;/script&gt;

php - $_GET 不反序列化/从选中的复选框中获取值

php - Javascript、PHP、C 和 C++ 的统一编码风格

javascript - 如何在循环中使用ajax发送单个请求

php - Laravel 关系计数()

php - 在 Laravel 5.2 中选择列值相等的行

javascript - 一旦获得焦点,将 RadioButton 值设置为 true,然后点击 asp :RadioButton 中的 Enter 按钮

javascript - 按属性嵌套/分组对象数组,忽略 null/undefined 并使用附加属性作为标签

php - 如何在Gridview Yii2中的条形码生成器中传递 "elementId"?

php - 如何在命令行上运行 php?