2017-03-16 80 views
0

我有个问题; 如何调用多个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承诺中使用它。

注意:您的参数必须作为数组传递。

谢谢

+0

我觉得你的问题是,后不工作与多维输入。只是简单的键值对。我也有这个问题。 – mtizziani

+2

您正在重新创建RPC/SOAP。为什么不考虑REST来解耦前端和后端? – n00dl3

+0

@mtizziani多维输入背后的推理是什么,你可以将它们传递给php并在那里重构它们? –

回答

0

改变你的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]); 
+0

谢谢,对不起,我只是试图理解这里,将json字符串数组传递给函数的原因是什么,这将需要在函数方面进行进一步的操作,而不添加额外的安全性或更多的选项。如果在发送到PHP之前还有其他原因需要在Json中对数组进行编码,请让我知道。 –

+0

我几个星期前也问过这个问题。这里是链接 - > http://stackoverflow.com/questions/41717877/difference-between-filter-input-and-direct-acces-on-post-after-objective-ajax。答案是,在通过post发送的每个键值对中,值必须是字符串类型。否则会产生负面的副作用。我认为$ _POST被定义为filter_input函数调用它时的字符串数组 – mtizziani