如何通过JavaScript调用PHP函数?
我试图将外部PHP文件中的PHP函数调用为JavaScript脚本。我的代码不同而且很大,所以我在这里编写了一个示例代码 这是我的PHP代码:如何通过JavaScript调用PHP函数?,javascript,php,function,Javascript,Php,Function,我试图将外部PHP文件中的PHP函数调用为JavaScript脚本。我的代码不同而且很大,所以我在这里编写了一个示例代码 这是我的PHP代码: 这是我的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
这是我的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>
var phpadd=add(1,2)//调用php add函数
var phpmult=mult(1,2)//调用php mult函数
var phpdivide=除以(1,2)//调用php divide函数
这就是我想做的
我的原始PHP文件不包含这些数学函数,但思想是相同的
如果它没有一个合适的解决方案,那么您可以建议一个替代方案,但它应该从外部PHP调用值。试试这个
<script>
var phpadd= <?php echo add(1,2);?> //call the php add function
var phpmult= <?php echo mult(1,2);?> //call the php mult function
var phpdivide= <?php echo divide(1,2);?> //call the php divide function
</script>
var phpadd=//调用php add函数
var phpmult=//调用php mult函数
var phpdivide=//调用php divide函数
例如,如果您确实想将数据发送到php脚本,您可以执行以下操作:
php:
<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized
echo $a + $b;
?>
是的,您可以使用请求参数中的数据对服务器执行ajax请求,如下所示(非常简单): 请注意,下面的代码使用 而您的函数_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);
?>
试试看。我们的想法是将PHP与JS混合使用,这样两者都可以在客户端和服务器端工作。您需要创建一个API: js函数在web服务上执行AJAX请求
var mult = function(arg1, arg2)
$.ajax({
url: "webservice.php?action=mult&arg1="+arg1+"&arg2="+arg2
}).done(function(data) {
console.log(data);
});
}
在php方面,为了执行propre函数,您必须检查action参数(基本上是$u GET[“action”]变量上的switch语句)index.php
<body>
...
<input id="Div7" name="Txt_Nombre" maxlenght="100px" placeholder="Nombre" />
<input id="Div8" name="Txt_Correo" maxlenght="100px" placeholder="Correo" />
<textarea id="Div9" name="Txt_Pregunta" placeholder="Pregunta" /></textarea>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".Txt_Enviar").click(function() { EnviarCorreo(); });
});
function EnviarCorreo()
{
jQuery.ajax({
type: "POST",
url: 'servicios.php',
data: {functionname: 'enviaCorreo', arguments: [$(".Txt_Nombre").val(), $(".Txt_Correo").val(), $(".Txt_Pregunta").val()]},
success:function(data) {
alert(data);
}
});
}
</script>
...
$(文档).ready(函数(){
$(.Txt_Enviar”)。单击(函数(){EnviarCorreo();});
});
函数enviracorreo()
{
jQuery.ajax({
类型:“POST”,
url:'servicios.php',
数据:{functionname:'enviaCorreo',参数:[$(“.Txt_Nombre”).val(),$(“.Txt_Correo”).val(),$(“.Txt_Pregunta”).val()},
成功:功能(数据){
警报(数据);
}
});
}
servicios.php
<?php
include ("correo.php");
$nombre = $_POST["Txt_Nombre"];
$correo = $_POST["Txt_Corro"];
$pregunta = $_POST["Txt_Pregunta"];
switch($_POST["functionname"]){
case 'enviaCorreo':
EnviaCorreoDesdeWeb($nombre, $correo, $pregunta);
break;
}
?>
correo.php
<?php
function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
{
...
}
?>
我为自己写了一些脚本,它正在工作。。我希望它对你有用
<?php
if(@$_POST['add'])
{
function add()
{
$a="You clicked on add fun";
echo $a;
}
add();
}
else if (@$_POST['sub'])
{
function sub()
{
$a="You clicked on sub funn";
echo $a;
}
sub();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<input type="submit" name="add" Value="Call Add fun">
<input type="submit" name="sub" Value="Call Sub funn">
<?php echo @$a; ?>
</form>
使用document.write
比如说,
<script>
document.write(' <?php add(1,2); ?> ');
document.write(' <?php milt(1,2); ?> ');
document.write(' <?php divide(1,2); ?> ');
</script>
文件。写(“”);
文件。写(“”);
文件。写(“”);
这对我来说非常合适:
要调用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
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
<?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;
}
?>
//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代码保持相等,返回值将被回显:
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
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
<?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;
}
?>
//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.
});
我创建了这个库,可能对你有所帮助。
例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- include MyPHP.js -->
<script src="MyPHP.js"></script>
<!-- use MyPHP class -->
<script>
const php = new MyPHP;
php.auth = 'hashed-key';
// call a php class
const phpClass = php.fromClass('Authentication' or 'Moorexa\\Authentication', <pass aguments for constructor here>);
// call a method in that class
phpClass.method('login', <arguments>);
// you can keep chaining here...
// finally let's call this class
php.call(phpClass).then((response)=>{
// returns a promise.
});
// calling a function is quite simple also
php.call('say_hello', <arguments>).then((response)=>{
// returns a promise
});
// if your response has a script tag and you need to update your dom call just call
php.html(response);
</script>
</body>
</html>
<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
resultObj.html(result.join('<br>'));
});
$system('ls -l').then(function(result) {
resultObj.append(result);
});
$str_replace(' ').then(function(result) {
resultObj.append(result);
});
// Chaining functions
$testfn(34, 56).exec(function(result) { // first call
return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
resultObj.append('result: ' + result + '<br><br>');
});
</script>
页面标题
const php=新的MyPHP;
php.auth='哈希键';
//调用php类
const phpClass=php.fromClass('Authentication'或'Moorexa\\Authentication',);
//调用该类中的方法
方法('login',);
//你可以继续在这里锁链。。。
//最后,让我们叫这个班
调用(phpClass).then((响应)=>{
//回报一个承诺。
});
//调用函数也很简单
php.call('say_hello',)。然后((response)=>{
//回报承诺
});
//如果您的响应有一个脚本标记,并且需要更新dom调用,只需调用
html(响应);
我创建了这个库,您可以从github下载,随时随地使用
该库允许将php函数和类方法导入javascript浏览器环境,因此可以使用它们的实际名称作为javascript函数和方法进行访问。代码使用javascript承诺,因此可以链接函数返回
我希望它对你有用
例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- include MyPHP.js -->
<script src="MyPHP.js"></script>
<!-- use MyPHP class -->
<script>
const php = new MyPHP;
php.auth = 'hashed-key';
// call a php class
const phpClass = php.fromClass('Authentication' or 'Moorexa\\Authentication', <pass aguments for constructor here>);
// call a method in that class
phpClass.method('login', <arguments>);
// you can keep chaining here...
// finally let's call this class
php.call(phpClass).then((response)=>{
// returns a promise.
});
// calling a function is quite simple also
php.call('say_hello', <arguments>).then((response)=>{
// returns a promise
});
// if your response has a script tag and you need to update your dom call just call
php.html(response);
</script>
</body>
</html>
<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
resultObj.html(result.join('<br>'));
});
$system('ls -l').then(function(result) {
resultObj.append(result);
});
$str_replace(' ').then(function(result) {
resultObj.append(result);
});
// Chaining functions
$testfn(34, 56).exec(function(result) { // first call
return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
resultObj.append('result: ' + result + '<br><br>');
});
</script>
$scandir(指向文件夹的路径)。然后(函数(结果){
html(result.join(“
”);
});
$system('ls-l')。然后(函数(结果){
结果追加(结果);
});
$str_replace(“”)。然后(函数(结果){
结果追加(结果);
});
//链接函数
$testfn(34,56).exec(函数(结果){//第一次调用
返回$testfn(34,result);//以第一次调用的结果作为参数的第二次调用
}).exec(函数(结果){
resultObj.append('result:'+result+'
');
});
无效函数
<?php
function printMessage() {
echo "Hello World!";
}
?>
<script>
document.write("<?php printMessage() ?>");
</script>
<?php
function getMessage() {
return "Hello World!";
}
?>
<script>
var text = "<?php echo getMessage() ?>";
</script>
文件。填写(“”);
值返回功能
<?php
function printMessage() {
echo "Hello World!";
}
?>
<script>
document.write("<?php printMessage() ?>");
</script>
<?php
function getMessage() {
return "Hello World!";
}
?>
<script>
var text = "<?php echo getMessage() ?>";
</script>
var text=“”;
php是服务器端,js是客户端。你需要在get/posts中使用ajax或页面刷新,或者尝试创建一个与js等效的函数?以及如何在不同的功能和组件下使用它?是的,回答很好。。。我只是想补充一下关于jQuery的说明,这会变得更慢。另一种选择是使用浏览器原生XMLHttpRequest,例如hereheader('Content-Type:application/json');我想你不需要这一行。我想在输入发生变化时调用php函数,所以这给了我一个线索,我最终使用了fetch,谢谢。让我们试试我的解决方案,对我来说很有效!在你对任何问题发表评论之后!尽管这个解决方案有效,但它并不是一个干净的好方法。它在客户机和服务器代码之间具有紧密的依赖关系。更好的设计是使用ajax向具有php函数调用的php页面发送请求。var num1;var num2;var phpadd=可以这样调用函数吗???@Shadi-我很好奇,“客户端和服务器代码之间的紧密依赖”有什么不对?是否存在潜在问题,或者这只是一个“ti”问题