jquery 如何使用JavaScript从一个PHP文件中调用另一个PHP文件中的类方法?

8yparm6h  于 2023-11-17  发布在  jQuery
关注(0)|答案(1)|浏览(118)

此问题在此处已有答案

How can I call PHP functions by JavaScript?(13个回答)
12天前关门了。
我有一个这样的类

class TestClass() {
   public function TestFunction() {
        return "TESTING"
    }
}

字符串
我在另一个php文件中导入类,

use \Path\To\TestClass

<script>
how to call it here ?
</script>


在这里,我想用js调用这个类中存在的方法,我该怎么做呢?

7xllpg7q

7xllpg7q1#

您可以发送http请求,因为PHP是服务器端语言,而JavaScript是客户端语言。JavaScript在浏览器中运行,而PHP在服务器上运行。
创建一个这样的脚本来用JSON发送响应

class TestClass {
    public function TestFunction() {
        return "TESTING";
    }
}

$testClass = new TestClass();

if (isset($_GET['action']) && $_GET['action'] === 'callTestFunction') {
    $result = $testClass->TestFunction();
    echo json_encode(["result" => $result]);
}

字符串
在html文件中,

<script>
    $(document).ready(function() {
        $.ajax({
            url: 'TestClass.php?action=callTestFunction',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                console.log(data.result); // Output--"TESTING"
            },
            error: function(xhr, status, error) {
                console.error("Error:", error);
            }
        });
    });
</script>


然后,确定在html中的脚本上方添加此内容

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

相关问题