1

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 の代替関数はありますか? ありがとう。

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
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 に答える
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 に答える