我想从jquery ajax调用Php用户定义函数


i want to Call Php user define function from jquery ajax

我想从jquery ajax( $.ajax({}) ) 调用php用户定义函数

我的ajax代码在index.php中,php用户定义函数在functions.php 中

两者都在同一文件夹中

这是我的index.php代码

<html>
<head>
<script src="headerfiles/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function()
{
        $("#display").click(function()
        {
                var mobile=$("#mobile").val();
                $.ajax({
                method:"post",
                url:"functions.php",
                success:function(name){alert(name);}
                });
        });
});
</script>
</head>
</body>
<input type="text" id="mobile" name="mobile" />
<input type="button" id="display" name="display" value="Display" />
</body>
</html>

和functions.php代码为

function fetch_name($mobile)
{      
    $name="my query............"
    echo $name;
    //or
    return $name;
}

我想在index.php页面中显示名称

您可以执行此

在js中添加:

data:{fc : 'fetch_name'};

php中的

$fc = $_POST['fc'];
$fc();
function fetch_name($mobile)
{      
  $name="my query............"
  echo $name;
  //or
  return $name;
}
//In your ajax send a post param 

$.ajax({
method:"post",
url:"functions.php",
data: { 
        'foo': 'function_name', 
    },
............
.................
In your functions.php
//capture the post param foo to get the function name 
//set it to null if its not sent
$foo  = isset($_POST['foo']) ? $_POST['foo'] : null;
//if foo is set call the function
if($foo){
$foo();
}

p.S我不知道你为什么要从functions.php调用函数,而你可以从index.php调用它并包含function.php。

根据您的脚本Html:-

<html>
<head>
<script src="headerfiles/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
    $("#display").click(function(e)
    {
        var postData = $('#mobile').val(); // Data which you may pass.
        var formURL = 'function.php'; // Write callback script url here
        $.ajax(
        {
        url : formURL,
        type: "POST",
        data : postData,
        success:function(data, textStatus, jqXHR)
        {
            alert(data);
            //data: return data from server
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //if fails     
        }
        });
    });
});
</script>
</head>
</body>
<input type="text" id="mobile" name="mobile" />
<input type="button" id="display" name="display" value="Display" />
</body>
</html>

在function.php中:-

<?php
    // Post Value
    $mobile = isset($_POST['mobile']) ? $_POST['mobile'] : '';
    fetch_name($mobile);
    function fetch_name($mobile) {
      echo $mobile;
     // Your function body goes here.
       exit;
    }
?>