這項工作非常適合我:
要調用PHP函數(參數也行)就可以了,像很多人說,送參數打開PHP文件,從那裏檢查參數的值來調用函數。但是你也可以做很多人說這是不可能的:直接調用正確的PHP函數,而不需要向PHP文件添加代碼。
我找到了一種方法:
這對JavaScript:
function callPHP(expression, objs, afterHandler) {
expression = expression.trim();
var si = expression.indexOf("(");
if (si == -1)
expression += "()";
else if (Object.keys(objs).length > 0) {
var sfrom = expression.substring(si + 1);
var se = sfrom.indexOf(")");
var result = sfrom.substring(0, se).trim();
if (result.length > 0) {
var params = result.split(",");
var theend = expression.substring(expression.length - sfrom.length + se);
expression = expression.substring(0, si + 1);
for (var i = 0; i < params.length; i++) {
var param = params[i].trim();
if (param in objs) {
var value = objs[param];
if (typeof value == "string")
value = "'" + value + "'";
if (typeof value != "undefined")
expression += value + ",";
}
}
expression = expression.substring(0, expression.length - 1) + theend;
}
}
var doc = document.location;
var phpFile = "URL of your PHP file";
var php =
"$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
"$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
"set_include_path($folder);include $fileName;" + expression + ";";
var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
$.ajax({
type: 'GET',
url: url,
complete: function(resp){
var response = resp.responseText;
afterHandler(response);
}
});
}
這一個PHP文件,該文件是不是你的PHP文件,但另一個,這條路徑寫入在url
JS函數變量callPHP
,它需要評估PHP代碼。此文件被稱爲「phpCompiler.php」和它在你的網站的根目錄:
<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
所以,你的PHP代碼保持等於除了返回值,這將是附和道:
<?php
function add($a,$b){
$c=$a+$b;
echo $c;
}
function mult($a,$b){
$c=$a*$b;
echo $c;
}
function divide($a,$b){
$c=$a/$b;
echo $c;
}
?>
我建議你要記住,jQuery是必需的:
從谷歌CDN下載:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
或Microsoft CDN:「我更喜歡谷歌! :)」
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
更好的是從兩個CDN中的一個下載文件,並把它作爲本地文件,那麼你的網站的速度更快!
選擇的啓動時加載的是你!
!
現在你說完我只是告訴你如何使用
callPHP
功能這是JavaScript調用PHP:
//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
'num1' : 1,
'num2' : 2
},
function(output) {
alert(output); //This to display the output of the PHP file.
});
php是服務器端JS是客戶端。您需要使用ajax或頁面刷新gets/posts或嘗試創建一個js等效函數。 – Class