如何通过 ajax 执行 PHP 函数



如何使用ajax执行PHP函数?我的脚本页面上有多个函数,但我想调用一个函数。

<?php
    function one(){return 1;}
    function two(){return 2;}
?>

$("#form").on('submit',(function(e){
    e.preventDefault();
    
    $.ajax({
        url: "process.php",
        type: "POST",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData:false,
        success: function(response){
            alert(response);
        }
    });
}));
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form action="" method="POST" id="form">
    <input type="text" name="text" id="text" />
    <button type="submit" id="submit">Upload</button>
</form>

使用 Get param "action"

$("#form").on('submit', (function(e) {
  e.preventDefault();
  $.ajax({
    url: "process.php?action=one",
    type: "POST",
    data: new FormData(this),
    contentType: false,
    cache: false,
    processData: false,
    success: function(response) {
      alert(response);
    }
  });
}));
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form action="" method="POST" id="form">
  <input type="text" name="text" id="text" />
  <button type="submit" id="submit">Upload</button>
</form>

然后在您的过程中.php文件中,只需捕获"动作"

function one(){
 return 1;
}
function two(){
 return 2;
}

if ( isset($_GET['key']) && !empty(isset($_GET['key'])) ) {
  $action = $_GET['key'];
  
  switch( $action ) {
    case "one":{
       return 1; // or call here one();
    }break;
    case "two":{
       return 2; // or call here two();
    }break;
    default: {
      // do not forget to return default data, if you need it...
    }
  }
}

您可以通过 AJAX 调用和 PHP 代码中的一些更改,通过 AJAX 调用 PHP 代码的特定函数。

例如:阿贾克斯:

$.ajax({
    url: "yourphpfile.php",
    data: "function=one", // or function=two if you want the other to be called
   /* other params as needed */
});

然后在 yourphpfile .php 代码中,

<?php
function one(){return 1;}
function two(){return 2;}
    if(isset($_GET['function'])) {
        if($_GET['function'] == 'one') {
            function one() // call function one
        } elseif($_GET['function'] == 'two') {
            //function two() // call function two
        }
    }
?>

最新更新