简体   繁体   English

如何通过 JavaScript 调用 PHP 函数?

[英]How can I call PHP functions by JavaScript?

I am trying to call a PHP function from an external PHP file into a JavaScript script.我正在尝试将外部 PHP 文件中的 PHP function 调用到 Z686155AF75A60AD3E9EZD 脚本中。 My code is different and large, so I am writing a sample code here.我的代码不同而且很大,所以我在这里写一个示例代码。

This is my PHP code:这是我的 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;
}
?>

This is my JavaScript code:这是我的 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>

So this is what I want to do.所以这就是我想做的。

My original PHP file doesn't include these mathematical functions but the idea is same.原来的 PHP 文件不包括这些数学函数,但想法是一样的。

If some how it doesn't have a proper solution, then may you please suggest an alternative, but it should call values from external PHP.如果它没有适当的解决方案,那么请您提出一个替代方案,但它应该从外部 PHP 调用值。

Yes, you can do ajax request to server with your data in request parameters, like this (very simple):是的,您可以使用请求参数中的数据向服务器发出 ajax 请求,如下所示(非常简单):

Note that the following code uses jQuery请注意,以下代码使用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);
                  }
            }
});

and your_functions_address.php like this:和 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);

?>

Try This试试这个

<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>

use document.write for example,使用 document.write 例如,

<script>
  document.write(' <?php add(1,2); ?> ');
  document.write(' <?php milt(1,2); ?> ');
  document.write(' <?php divide(1,2); ?> ');
</script>

You need to create an API : Your js functions execute AJAX requests on your web service您需要创建一个 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);
    });
  }

on the php side, you'll have to check the action parameter in order to execute the propre function (basically a switch statement on the $_GET["action"] variable)在 php 方面,您必须检查 action 参数才能执行适当的功能(基本上是 $_GET["action"] 变量上的 switch 语句)

index.php索引.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>

servicios.php服务端.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 correo.php

<?php
    function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
    { 
       ...
    }
?>

This work perfectly for me:这对我来说非常有用:

To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function.要调用 PHP 函数(也带有参数),您可以像很多人所说的那样,发送一个打开 PHP 文件的参数,然后从那里检查参数的值以调用该函数。 But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.但是你也可以做到很多人说这是不可能的:直接调用正确的 PHP 函数,而不向 PHP 文件添加代码。

I found a way:我找到了一个方法:

This for JavaScript:这适用于 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);
            }
        });
    }


This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code.这适用于一个 PHP 文件,它不是您的 PHP 文件,而是另一个,其路径写在JS 函数callPHPurl变量中,并且需要评估 PHP 代码。 This file is called 'phpCompiler.php' and it's in the root directory of your website:该文件名为“phpCompiler.php” ,位于您网站的根目录中:

<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
    eval(trim($line, " ") . ";");
?>


So, your PHP code remain equals except return values, which will be echoed:因此,除了返回值之外,您的 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;
}
?>


I suggest you to remember that jQuery is required:我建议你记住 jQuery 是必需的:
Download it from Google CDN:从谷歌 CDN 下载:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

or from Microsoft CDN: "I prefer Google! :)"或来自 Microsoft CDN:“我更喜欢 Google!:)”

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>

Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!更好的是从两个 CDN 之一下载文件并将其作为本地文件,这样您的网站的启动加载速度会更快!

The choice is to you!选择权在你!


Now you finished! 现在你完成了! I just tell you how to use callPHP function. 我只是告诉你如何使用callPHP函数。 This is the JavaScript to call PHP: 这是调用 PHP 的 JavaScript:

 //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. });

If you actually want to send data to a php script for example you can do this:例如,如果您实际上想将数据发送到 php 脚本,您可以这样做:

The php: php:

<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized

echo $a + $b;
?>

Js (using jquery): js(使用jquery):

$.post("/path/to/above.php", {a: something, b: something}, function(data){                                          
  $('#somediv').html(data);
});

I wrote some script for me its working .. I hope it may useful to you我为我写了一些脚本它的工作..我希望它对你有用

<?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>

Void Function虚空函数

<?php
function printMessage() {
    echo "Hello World!";
}
?>

<script>
    document.write("<?php printMessage() ?>");
</script>

Value Returning Function值返回函数

<?php
function getMessage() {
    return "Hello World!";
}
?>

<script>
    var text = "<?php echo getMessage() ?>";
</script>

Try looking at CASSIS .尝试查看CASSIS The idea is to mix PHP with JS so both can work on client and server side.这个想法是将 PHP 与 JS 混合在一起,这样两者都可以在客户端和服务器端工作。

I created this library JS PHP Import which you can download from github, and use whenever and wherever you want.我创建了这个库JS PHP Import ,你可以从 github 下载,随时随地使用。

The library allows importing php functions and class methods into javascript browser environment thus they can be accessed as javascript functions and methods by using their actual names.该库允许将 php 函数和类方法导入 javascript 浏览器环境,因此可以通过使用它们的实际名称将它们作为 javascript 函数和方法进行访问。 The code uses javascript promises so you can chain functions returns.该代码使用 javascript 承诺,因此您可以链接函数返回。

I hope it may useful to you.我希望它对你有用。

Example:例子:

<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>

I created this library, may be of help to you.我创建了这个库,可能对你有帮助。 MyPHP client and server side library MyPHP 客户端和服务器端库

Example:例子:

<!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>

I made a version only using js, without using any dependencies.我只使用 js 制作了一个版本,没有使用任何依赖项。 I think this is the shorest solution but probably not the best one since it doens't check for any errors.我认为这是最可靠的解决方案,但可能不是最好的解决方案,因为它不检查任何错误。

javascript javascript

var a = 1;
var b = 2;
function add(){
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "YOUR_SERVER/function.php?a="+a+"&b="+b, false );
  xmlHttp.send( null );
  return xmlHttp.responseText; 
}
var c = add(a, b)

function.php file function.php文件

<?php echo $_GET["a"] + $_GET["b"]?>

c = 3 c = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM