我有個問題; 如何調用多個PHP函數並將它們輸出到頁面上?用ajax動態調用PHP函數
現在我已經找到了一種方法,反正可以讓我知道我可以如何提高我的答案。 它完美的工作,我只想看看什麼可能是一個更好的方法。
AJAX CALL;
$.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承諾中使用它。
注意:您的參數必須作爲數組傳遞。
謝謝
我覺得你的問題是,後不工作與多維輸入。只是簡單的鍵值對。我也有這個問題。 – mtizziani
您正在重新創建RPC/SOAP。爲什麼不考慮REST來解耦前端和後端? – n00dl3
@mtizziani多維輸入背後的推理是什麼,你可以將它們傳遞給php並在那裏重構它們? –