How to call PHP function using jQuery ajax?

前端 未结 2 1994
日久生厌
日久生厌 2021-01-22 06:28

I have a file called myfunctions.php where I have a lot of functions, like

function sendForm(){
    //save form
}
function fn2(){
 //do something
}
 // Other fun         


        
相关标签:
2条回答
  • 2021-01-22 07:02
    $.ajax({
        //...
        data: {key1: "value1", key2: "value2", key3: "value3", type:0},
        //...
    });
    

    myfunctions.php:

    <?php
    //...
    if (!isset($_POST['type'])) { /* return something */ exit; }
    $type = $_POST['type'];
    if ($type == 0)
    {
        function1();
    } else if ($type == 1) {
        function2();
    } //etc.
    //...
    ?>
    
    0 讨论(0)
  • 2021-01-22 07:06

    In PHP

    <?php
    // create a list of approved function calls
    $approved_functions = array('sendForm','fn2');
    
    // check the $_GET['function'] and see if it matches an approved function
    if(in_array($_GET['function'], $approved_functions))
    {
        // call the approved function
        $_GET['function']();
    }
    
    function sendForm(){
        //save form
    }
    function fn2(){
     //do something
    }
    

    In AJAX

    // specify which function to call
    url: "myfunctions.php?function=sendForm",
    
    0 讨论(0)
提交回复
热议问题