Hoe kan ik PHP-functies aanroepen met JavaScript?

Ik probeer een PHP-functie vanuit een extern PHP-bestand aan te roepen in een JavaScript-script. Mijn code is anders en groot, dus ik schrijf hier een voorbeeldcode.

Dit is mijn PHP-code:

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

Dit is mijn JavaScript-code:

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

Dus dit is wat ik wil doen.

Mijn originelePHP-bestand bevat deze wiskundige functies niet, maar het idee is hetzelfde.

Als het op de een of andere manier geen goede oplossing heeft, kun je alsjebliefteen alternatief voorstellen, maar het zou waarden van externe PHP moeten aanroepen.


Antwoord 1, autoriteit 100%

Ja, u kunt een ajax-verzoek doen naar de server met uw gegevens in verzoekparameters, zoals dit (heel eenvoudig):

Houd er rekening mee dat de volgende code jQuery

gebruikt

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

en uw_functions_address.php als volgt:

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

Antwoord 2, autoriteit 50%

Probeer dit

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

Antwoord 3, autoriteit 15%

gebruik document.write
bijvoorbeeld,

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

Antwoord 4, autoriteit 10%

U moet een API maken:
Uw js-functies voeren AJAX-verzoeken uit op uw webservice

 var mult = function(arg1, arg2)
    $.ajax({
      url: "webservice.php?action=mult&arg1="+arg1+"&arg2="+arg2
    }).done(function(data) {
      console.log(data);
    });
  }

aan de php-kant moet je de actieparameter controleren om de propre-functie uit te voeren (in feite een switch-statement op de $_GET[“action”]-variabele)


Antwoord 5, autoriteit 7%

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>

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)
    { 
       ...
    }
?>

Antwoord 6, autoriteit 5%

Als je daadwerkelijk gegevens naar bijvoorbeeld een php-script wilt sturen, kun je dit doen:

De php:

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

Js (met jQuery):

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

Antwoord 7, autoriteit 4%

Ik heb een script voor me geschreven, het werkt.. Ik hoop dat je er iets aan hebt

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

Antwoord 8, autoriteit 4%

Dit werkt perfect voor mij:

Om een PHP-functie aan te roepen (ook met parameters) kun je, zoals veel mensen zeiden, een parameter sturen die het PHP-bestand opent en van daaruit de waarde van de parameter controleren om de functie aan te roepen. Maar je kunt ook doen dat veel mensen zeggen dat het onmogelijk is: direct de juiste PHP-functie aanroepen, zonder code aan het PHP-bestand toe te voegen.

Ik heb een manier gevonden:

Dit voor 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);
            }
        });
    }

Dit voor een PHP-bestand dat niet jouw PHP-bestand is, maar een ander, welk pad is geschreven inurlvariabele van JS-functiecallPHP, en het is vereist om PHP-code te evalueren. Dit bestand heet ‘phpCompiler.php’en staat in de hoofdmap van uw website:

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

Dus je PHP-code blijft gelijk, behalve de retourwaarden, die worden herhaald:

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

Ik raad je aan te onthouden dat jQuery vereist is:

Download het van Google CDN:

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

of van Microsoft CDN: “Ik geef de voorkeur aan Google! :)”

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

BETER is om het bestand van een van de twee CDNS te downloaden en deze als lokaal bestand te plaatsen, zodat de startup-lading van uw website sneller is!

De keuze is voor jou!

Nu klaar je! Ik zeg u gewoon hoe u callPHP-functie kunt gebruiken. Dit is het JavaScript om PHP te bellen:

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

Antwoord 9

Probeer te kijken naar cassis . Het idee is om PHP te mengen met JS, zodat beide kunnen werken aan de kant van de klant en de server.


Antwoord 10

Ik heb deze bibliotheek gemaakt JS PHP import die u kunt downloaden van GitHub, en gebruik wanneer en waar u maar wilt.

De bibliotheek maakt het importeren van PHP-functies en klassenmethoden in de JavaScript-browseromgeving, dus ze zijn toegankelijk als JavaScript-functies en -methoden door gebruik te maken van hun werkelijke namen. De code gebruikt JavaScript-beloftes, zodat u kunt kettingfuncties retourneren.

Ik hoop dat het nuttig kan zijn voor u.

Voorbeeld:

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

Antwoord 11

void-functie

<?php
function printMessage() {
    echo "Hello World!";
}
?>
<script>
    document.write("<?php printMessage() ?>");
</script>

Waarde retourfunctie

<?php
function getMessage() {
    return "Hello World!";
}
?>
<script>
    var text = "<?php echo getMessage() ?>";
</script>

Antwoord 12

Ik heb deze bibliotheek gemaakt, kan je helpen.
mypephp client en server zijbibliotheek

Voorbeeld:

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

Other episodes