簡體   English   中英

從 Javascript 腳本中執行 PHP function

[英]Execute a PHP function from within a Javascript script

我已經查看了這里的所有問題,但根本無法解決這個問題或讓它發揮作用。 我只是想使用一個按鈕來運行一個執行 php function 的腳本。

HTML:

<button id="update_submit" type="button" onClick="myFunction()">Update</button>

腳本:

                    <script>
                        function myFunction(){
                            if (document.getElementById("drug_text_name").value=="") {
                                alert( "I am an alert box!" );
                            } else {
                            $.ajax({url: "../script.php", success: function(result){
                                window.location.href = '../drug_manager.php';
                                }      
                                   });
                            }
                        }
                    </script>

PHP 文件:

<?php
// including the database connection file

    include_once("../../includes/dbh.inc.php");
    $result = mysqli_query($conn, "UPDATE drugs SET Drug_Name='$Drug_Name' ,Allergies='$Allergies' ,Side_effects='$Side_effects' ,Type_of_Medication='$Type_of_Medication',Dosage='$Dosage' WHERE Drug_ID=$Drug_ID");

?>

在這里,我希望它運行 SQL 查詢,然后將用戶重定向到頁面 /drug_manager.php。

首先,您不能在 JavaScript 中執行 PHP 函數,因為 PHP 在服務器端運行,而 JavaScript 在客戶端運行。 在您的示例中,您的 PHP 文件沒有執行任何操作,因為從未執行過測試 function。 如果您執行測試 function ajax 調用將被重定向到該位置,請在此處閱讀有關它的更多信息。

如果您希望用戶在單擊按鈕時被重定向,您可以在 window.location.href 的幫助下簡單地重定向他們,如下所示:

<script>
$("#update_submit").on('click', function(){
    window.location.href = '../script.php';
)};
</script>

If you want PHP to decide where the user should be redirected your PHP-file could return an URL and then you use window.location.href to that URL. 像這樣的東西:

PHP:

<?php
function test() {
    echo "drug_manager.php";
}
test();
?>

腳本:

<script>
$("#update_submit").on('click', function(){

    $.ajax({
       url: '../script.php',
       dataType: 'json',
       success: function(data){
           window.location.href = data;
       }
    });
)};
</script>

暫無
暫無

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

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