我有个问题; 如何调用多个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并在那里重构它们? –