如何通过 JavaScript 调用 PHP 函数? [英] How can I call PHP functions by JavaScript?

查看:24
本文介绍了如何通过 JavaScript 调用 PHP 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个 PHP 函数从外部 PHP 文件调用到 JavaScript 脚本中.我的代码不同而且很大,所以我在这里写了一个示例代码.

I am trying to call a PHP function from an external PHP file into a JavaScript script. My code is different and large, so I am writing a sample code here.

这是我的 PHP 代码:

This is my 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;
}
?>

这是我的 JavaScript 代码:

This is my 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>

这就是我想做的.

我的原始 PHP 文件不包含这些数学函数,但思路是一样的.

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.

推荐答案

是的,您可以使用请求参数中的数据向服务器发出ajax请求,如下所示(非常简单):

Yes, you can do ajax request to server with your data in request parameters, like this (very simple):

注意以下代码使用了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 像这样:

and your_functions_address.php like this:

    <?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 调用 PHP 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆