亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

如何透過JavaScript呼叫PHP函數(shù)?
P粉133321839
P粉133321839 2023-07-30 18:57:00
0
2
728
<p>我正在嘗試從一個(gè)外部的PHP檔案中呼叫PHP函數(shù)到JavaScript腳本中。我的程式碼比較複雜,所以我在這裡寫一個(gè)範(fàn)例程式碼。 </p><p>這是我的PHP程式碼:</p> <pre class="lang-php prettyprint-override"><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; } ?> </code></pre> <p>JS代碼:</p> <pre class="brush:php;toolbar:false;"><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></pre> <p>這就是我想要做的。 </p><p>我的原始PHP檔案沒有包含這些數(shù)學(xué)函數(shù),但思路是相同的。 </p><p>如果沒有合適的解決方案,您能否請(qǐng)?zhí)峁┨娲桨?,但它?yīng)該從外部的PHP檔案中呼叫值。 </p><p><strong></strong></p>
P粉133321839
P粉133321839

全部回覆(2)
P粉396248578

試下這個(gè)

<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>
P粉235202573

是的,您可以使用請(qǐng)求參數(shù)向伺服器發(fā)送帶有資料的Ajax請(qǐng)求,就像這樣(非常簡(jiǎn)單):

請(qǐng)注意,以下程式碼使用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);
                  }
            }
});

您的_functions_address.php檔案應(yīng)該像這樣:

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

?>
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板