Ajax URL可以成为PHP函数吗?

时间:2017-11-09 22:38:01

标签: php ajax

很抱歉,如果这太基础了,或者在某个地方得到了权威性的回答,那就是我。

我开始使用Ajax和PHP。我正在使用我页面上的一些按钮,每个按钮都需要从SQLite数据库中查找一些数据,并以某种方式在页面上呈现。

我的问题是,不是每个按钮都有一个.php页面,我怎么能让每个Ajax调用命中一个.php页面,但是引用一个要运行的函数,在其中我将检查/处理POST的内容?

这可能吗?如果是这样的话?我尝试使用如下语法:

 $.ajax({
            type: "POST",
            url: "functions.php?func=writeMsgAdd",
            data: { "contentid": contentID },
            success: function (data) {
                console.log("foobar: " + data );                    
            }
        });

页面是functions.pho,该页面包含一个名为writeMsgAdd()的函数,但没有运气。希望了解如何实现这一目标。

2 个答案:

答案 0 :(得分:3)

您的ajax电话应如下所示:

$.ajax({
    type: "POST",
    url: "functions.php",
    data: { "phpFunction":"function1", "contentid": contentID },
    success: function (data) {
        console.log("foobar: " + data );                    
    }
});

你的php文件应该如下所示:

$function = $_POST["phpFunction"] ;

if ($function == "function1") {

    //Code for function 1 goes here
}
else if ($function == "function2" {
    //Code for function 2 goes here
}
....
  

更新

以上方式,您只向ajax response发送一个值,如果您想发送多个变量,可以将dataType: json添加到您的ajax,然后在php中你必须返回一个json值。

$.ajax({
    type: "POST",
    dataType: json
    url: "functions.php",
    data: { "phpFunction":"function1", "contentid": contentID },
    success: function (data) {
        console.log("Val1: " + data.key1);
        console.log("Val2: " + data.key2);                    
    }
});

你的php函数必须以:

结尾
echo json_encode(array("key1"=>"val1", "key2"=>"val2")) ;
exit() ;

答案 1 :(得分:2)

您可以执行此操作,假设您将writeMsgAdd作为函数名称传递,并将contentid作为要传递给writeMsgAdd的参数:

客户端

$.ajax({
    type: "POST",
    url: "functions.php",
        data: { 
            "func": "writeMsgAdd",
            "contentid": contentID 
        },
        success: function (data) {
        console.log("foobar: " + data );                    
    }
});

服务器端:

<?php 
    $func = $_POST["func"] ;
    $contentid = $_POST['contentid'];
    call_user_func($func, $contentid);
?>

或者,如果你想为每个函数传递多个不同的参数,那么我会改用call_user_func_array:

客户端

$.ajax({
    type: "POST",
    url: "functions.php",
        data: { 
            "func": "writeMsgAdd",
            "args": JSON.stringify({"contentid": contentID})
        },
        success: function (data) {
        console.log("foobar: " + data );                    
    }
});

服务器端:

<?php 
    $func = $_POST["func"] ;
    $args = json_decode($_POST['args'], true);
    call_user_func_array($func, $args);
?>