ajax 执行php函数

Hen*_*nry 2 javascript php ajax jquery

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

<?php
    function one(){return 1;}
    function two(){return 2;}
?>
Run Code Online (Sandbox Code Playgroud)

<?php
    function one(){return 1;}
    function two(){return 2;}
?>
Run Code Online (Sandbox Code Playgroud)
$("#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);
        }
    });
}));
Run Code Online (Sandbox Code Playgroud)

Say*_*ara 7

使用获取参数“动作”

$("#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);
		  }
		});
	}));
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

然后在您的 process.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...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)