我有一个问题; 如何调用多个 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 promise 中使用它。
注意:您的参数必须作为数组传递。
谢谢
最佳答案
像这样改变你的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]);
关于javascript - 使用ajax动态调用PHP函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42828527/