使用ajax将JavaScript参数传递给PHP

问题描述 投票:-1回答:1

我需要能够将JavaScript变量发送到PHP函数。我能够让它适用于硬编码值,如下面的代码。

<button onclick="submitform()">Click me</button>
<script>
    function submitform(){
      document.write(' <?php send_mail('hello'); ?> ');
    }
</script>

<?php
    function send_mail($subject){
        //$subject => 'hello'
        //Do something with subject
    }
?>

但是,我无法用变量替换硬编码值。我还想找到另一种发出PHP函数调用的方法。我相信解决方案在于ajax请求。我现在找不到直接嵌入PHP代码的方法。所有其他的例子我都无法工作。如果可能的话,我也会很感激。谢谢!

javascript php html ajax
1个回答
2
投票

你可以使用表格来做到这一点:

 <form action="send_mail.php" method="post">
         <input type="text"  id="mail" name = "mail">
        <input type="submit" class="btn" value="Send Mail">
    </form>

然后,您可以使用send_mail.php页面中的$ _POST [“mail”]访问邮件

另一种方法是ajax:

$.ajax({ url: '/send_mail.php',
         data: {action: 'sendEmail', mymail:$('#mail').val()},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

然后在send_mail.php页面中,您可以执行以下操作:

 if(isset($_POST['action']) && !empty($_POST['action'])) {
        $action = $_POST['action'];
    $mail = $_POST['mymail'];

        switch($action) {
            case 'sendEmail' : send_email();break;
            // ...etc...
        }
    }

同一页面调用的演示:

<?php

if(isset($_GET['action'])=='myfunc') {
    echo  "Hello";
}
?>

<form action="?action=myfunc" method="post">
    <input type="text"  id="mail" name = "mail">
    <input id="clickMe" type="submit" value="clickme"/>
© www.soinside.com 2019 - 2024. All rights reserved.