我正在尝试将外部 PHP 文件中的 PHP 函数调用到 JavaScript 脚本中。我的代码不同而且很大,所以我在这里写一个示例代码。
这是我的 PHP 代码:
<?php
function add($a,$b){
$c=$a+$b;
return $c;
}
function mult($a,$b){
$c=$a*$b;
return $c;
}
function divide($a,$b){
$c=$a/$b;
return $c;
}
?>
这是我的 JavaScript 代码:
<script>
var phpadd= add(1,2); //call the php add function
var phpmult= mult(1,2); //call the php mult function
var phpdivide= divide(1,2); //call the php divide function
</script>
这就是我想做的。
我的原始 PHP 文件不包含这些数学函数,但思路是一样的。
如果某些方法没有合适的解决方案,那么您可以请提出一个替代方案,但它应该从外部 PHP 调用值。
最佳答案
是的,您可以使用请求参数中的数据向服务器发出 ajax 请求,就像这样(非常简单):
请注意,以下代码使用了 jQuery
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
和 your_functions_address.php 这样:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
关于javascript - 如何通过 JavaScript 调用 PHP 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15757750/