簡體   English   中英

將JavaScript確認框的結果分配給PHP變量

[英]Assigning the result of a JavaScript confirm box to a PHP variable

//this is in php
function msgbox($msg, $type)
    {
    if ($type == "alert")
        {
        // Simple alert window
        ?> <script language="JavaScript"> alert("<? echo $msg; ?>"); </script> <?
        }
    elseif ($type == "confirm")
        {
        // Enter Confirm Code Here and assign the $result variable for use
        // Should include "OK" and "Cancel" buttons.
        ?>
           <script language="JavaScript">
           if (confirm("<? echo $msg; ?>"))
                {
                <? $result == "ok"; ?>
                }
           else
                {
                <? $result == "cancel"; ?>
                }
           </script>
        <?
        }
    }



if ($page_title->exists())

{msgbox("page exists,do you want to delete", "confirm");

}      
 if ($result == "ok")
//code..

問題是我認為$result不會從確認框中讀取值,因為沒有執行if子句,並且程序流將流向沒有if子句的地方。

您不能以這種方式將服務器端代碼(PHP)與客戶端代碼混合在一起。 為了使javascript更改PHP狀態,您需要進行HTTP調用(經常使用AJAX)。

您需要閱讀PHP教程,並確保您掌握了這些概念。

只要頁面是在服務器端創建然后發送給用戶的,就可以使用Ajax來創建您要完成的任務,您將無法直接篡改$ result變量。 首先要掌握AJAX的參考以及使用方法。

關於使用jQuery的Ajax的101條文章(sitepoint.com)

使用jQuery和PHP輕松實現AJAX

Client.html

<!--some html...-->
<a class="ajax" href="/delete.php?title=some+title">Delete action link</a>

<script type="text/javascript">
// assuming jQuery has been loaded
$(function () {
    $('a.ajax').click(function () {
        // get link's href, get main url part and query part
        var link = $(this).attr('href');
        var route = link.substring(0, link.lastIndexOf('?'));
        var query = link.substring(link.lastIndexOf('?') + 1);

        // perform ajax call, to the main part of the link, with data
        $.ajax({
            type: "GET",
            url : route,
            data : query,
            success : function (data) {
                if (data === '1') {
                    window.alert('page removed');
                } else {
                    window.alert('error');
                }
            }
        });

        // prevent default behavior
        return false;
    });
});    
</script>

還有一個delete.php腳本,它以$ _GET ['title']作為參數

<?php
    $title = $_GET['title'];
    if ($pages->contain($title)) {
        $pages->remove($title);
        echo '1';
    }
?>

注意,這只是簡化了,以向您展示如何完成一個簡單的AJAX調用

您正在使用短標簽,請確保已從php.ini文件中將其打開,否則php代碼不會在您的代碼中執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM