如何使用jQuery ajax调用PHP函数?

时间:2022-10-23 08:12:38

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

我有一个名为myfunctions.php的文件,我有很多功能,比如

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

and the jquery code,

和jquery代码,

$.ajax({
    url: "myfunctions.php",
    type: "POST",
    contentType: "application/x-www-form-urlencoded",
    data: {key1: "value1", key2: "value2", key3: "value3"},
    complete: function(){
        //completado
        alert("complete");
    }
});

I need call specific function in this file; for example sendForm(). How can I do that?

我需要在这个文件中调用特定的函数;例如sendForm()。我怎样才能做到这一点?

2 个解决方案

#1


3  

In PHP

在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

在AJAX中

// specify which function to call
url: "myfunctions.php?function=sendForm",

#2


1  

$.ajax({
    //...
    data: {key1: "value1", key2: "value2", key3: "value3", type:0},
    //...
});

myfunctions.php:

myfunctions.php:

<?php
//...
if (!isset($_POST['type'])) { /* return something */ exit; }
$type = $_POST['type'];
if ($type == 0)
{
    function1();
} else if ($type == 1) {
    function2();
} //etc.
//...
?>

#1


3  

In PHP

在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

在AJAX中

// specify which function to call
url: "myfunctions.php?function=sendForm",

#2


1  

$.ajax({
    //...
    data: {key1: "value1", key2: "value2", key3: "value3", type:0},
    //...
});

myfunctions.php:

myfunctions.php:

<?php
//...
if (!isset($_POST['type'])) { /* return something */ exit; }
$type = $_POST['type'];
if ($type == 0)
{
    function1();
} else if ($type == 1) {
    function2();
} //etc.
//...
?>