【问题标题】:Automatticly instantiate PHP class with JavaScript HTTP request使用 JavaScript HTTP 请求自动实例化 PHP 类
【发布时间】:2014-12-27 18:59:00
【问题描述】:

我正在使用这个(标准)JavaScript 函数来调用 PHP 文件并向其发送数据:

/**
 * The PHP file which receives the data
 *
 * @type {string} The php filename
 */
const INSTALL_FILE = "install.php";

/**
 * Passes roadTaxData to the php install file which could be get with the $_POST operator
 */
function passToPHP (paramName, data) {
    var httpc = new XMLHttpRequest(); // simplified for clarity"
    httpc.open("POST", INSTALL_FILE, true); // sending as POST

    httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    /*
     Test purposes
     */
    httpc.onreadystatechange = function () { //Call a function when the state changes.
        if (httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
            console.log(httpc.responseText); // some processing here, or whatever you want to do with the response
        }
    };
    httpc.send(paramName + "=" + data);
}

在我的 PHP 文件中,我正在使用以下代码:

header('Content-Type: application/json');

$road_tax_data = json_decode($_POST['road-tax_data'], true);

return new RoadTaxDataParser($road_tax_data);

有没有办法自动实例化 RoadTaxDataParser 类?

【问题讨论】:

  • 是什么让您认为 PHP 不会自动创建 RoadTaxDataParser 类的实例?
  • @Bjorn 之间有一个文件。 install.php 和类所在的文件。
  • @Bjorn 据我了解 OPs 问题,他想省略 return new RoadTaxDataParser($road_tax_data); 并根据请求进行自动加载。
  • 我无法弄清楚您的想法,但您根本无法通过网络发送 PHP 对象并从 JavaScript 中使用它。您的脚本必须打印 JavaScript 可以解析的内容(可能是 JSON)。
  • @AxelAmthor 完全正确。

标签: javascript php oop


【解决方案1】:

您可以实现一些更通用的“index.php”,它会自动实例化从某个抽象类继承或实现接口的类,即

然后您可以将请求的类名作为参数或路径传递。

但这不会是完全通用的,也不是自动的,它只是能够完成您的应用程序。

您必须注意很多安全问题,以防止人们加载和实例化任意(有害)类。

这个概念可能倾向于 JSP 中的“servlet”思想,您可能正在 PHP 中寻找它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多