簡體   English   中英

如何使用jQuery ajax調用PHP函數?

[英]How to call PHP function using jQuery ajax?

我有一個名為myfunctions.php的文件,其中有很多功能,例如

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

和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");
    }
});

我需要在該文件中調用特定的函數; 例如sendForm() 我怎樣才能做到這一點?

在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
}

在AJAX中

// specify which function to call
url: "myfunctions.php?function=sendForm",
$.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.
//...
?>

暫無
暫無

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

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