使用Ajax的PHP函数调用

使用Ajax的PHP函数调用

问题描述:

我试图调用一个PHP函数,当一个HTML按钮clicked.i已经做了一些搜索,发现其不可能直接做到这一点,我应该使用AJAX。 所以这是我的尝试,到目前为止未working.this是我的test.php的,功能也在这个页面。

I am trying to call a php function when an HTML button is clicked.i have done some searching and found that its impossible to do this directly and i should use ajax. so this is my attempt so far which is not working.this is my test.php and the function is also in this page.

   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('.NextPage').on('click', function() {
                $.ajax({
                    url: 'test.php',
                    data: {x: 1},
                    type: 'POST',
                    dataType: 'JSON',
                    success: function(response) {
                        alert(response);
                    }
                });

            });
        });
    </script>
     </head>
     <body>

    <button type="button" class="NextPage">go to nextpage</button> 

    <?php
    if (isset($_POST['x'])) {
        if ($_POST['x'] == 1) {
            $data = function1();
            echo json_encode($data);
            exit;
        }
    }

    function function1() {
        return 'Hi user! im function #1';
    }

    function function2() {
        return 'Hi user! im function #2';
    }
    ?>

获得Ajax调用的x的值。

get the value of the x from ajax call.

$ X = $ _ POST ['X'];

$x = $_POST['x'];

然后使用它。

修改

首先,你必须检查你的天气变量设置或不..

First you have to check weather your variable is set or not..

if(isset($_POST[x]))
{
$x = $_POST['x'];
}

试试这个