javascript - 使用ajax动态调用PHP函数

标签 javascript php jquery ajax function

我有一个问题; 如何调用多个 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/

相关文章:

jquery - jquery 中的最终输出

javascript - 相互检查数组变量

javascript - 在javascript中使用datauri渲染图像

php - wordpress 主题中 <em> 的未知输出

javascript - Jquery SlideToggle需要点击2次

javascript - 动态网格 - 显示内联 block

javascript - 如何在 Javascript 中检索单选按钮值

javascript - 在 jquery.load 页面中使用 angularjs

php - 'safe' json_decode( ,,, ) 以防止耗尽内存

PHP:如何从当前类中使用的特征方法调用父方法?