如何在条件PHP语句中使用JS确认?
PHP在JS之前首先执行,但是如果数据不是空的,是否有一种简单的方法可以输出确认对话框(如Javascript确认),如以下条件PHP语句:如何在条件PHP语句中使用JS确认?,php,javascript,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
<?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
}
我喜欢将数据和代码分开,因此我喜欢从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创建JS变量时,我总是使用json_encode来避免
//使用新行和引号编码问题。
var isDataEmpty=;
如果(!isDataEmpty){
如果(确认(“某些消息”)){
覆盖现有数据();
}
}否则{
//进行
}
您可以让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>
$(文档).ready(函数(){
var answer=confirm(“您确定要覆盖吗?”);
//数据是空的
});
参见下面的代码
<?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
}
您应该尽量减少PHP和JS的混合,请参见我的答案,JS和PHP只在一行中交互。使用echo生成HTML非常难理解。您在两个地方编写了不必要的脚本标记(并且犯了在两个地方添加language=“javascript”
的错误)