簡體   English   中英

用ajax動態調用PHP函數

[英]Dynamically call PHP Function with ajax

我有一個問題; 一個人如何調用多個PHP函數並將它們輸出到頁面上?

現在,我找到了一種方法,無論如何可以讓我知道如何改善答案。 它運行完美,我只想看看有什么更好的方法。

AJAX通話;

$.ajax({ 
    url: 'functioncalls.php', //URL TO PHP FUNCTION CONTROL
    data: {call: 'Login', parameters: {Username, Password}}, //CALL the function name with an array of parameters
    type: 'post'
}).done( function( Output ){
    try{
     Output  = JSON.parse(Output); // see if out put is json as that is what we will pass back to the ajax call
    } catch (e){
        alert('Error calling function.');
    }
});

PHP“ functioncalls.php”頁面

if(isset($_POST['call']) && !empty($_POST['call'])){ //check if function is pasted through ajax
    print call_user_func_array($_POST['call'], $_POST['parameters']);//dynamically get function and parameters that we passed in an array
}

PHP函數-確保您的函數位於頁面上或包含在頁面中

function Login($Username, $Password){
    // function control
    return json_encode($return);// return your json encoded response in value or array as needed
}

就是這樣,您只需要調用任何函數並將其用於已完成的ajax許諾中,便無需其他任何操作。

注意:您的參數必須作為數組傳遞。

謝謝

像這樣改變你的ajax請求

$.ajax({ 
    url: 'functioncalls.php', //URL TO PHP FUNCTION CONTROL
    data: {call: 'Login', parameters: JSON.stringify([Username, Password])}, //CALL the function name with an array of parameters
    type: 'post'
}).done( function( Output ){
    try{
     Output  = JSON.parse(Output); // see if out put is json as that is what we will pass back to the ajax call
    } catch (e){
        alert('Error calling function.');
    }
});

在php中,您必須執行以下操作:

$params = json_decode($_POST['parameters']);
login($params[0], $params[1]);

暫無
暫無

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

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