2017-03-16 79 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