使用JavaScript HTTP请求自动实例化PHP类
我使用此标准JavaScript函数调用PHP文件并向其发送数据:使用JavaScript HTTP请求自动实例化PHP类,javascript,php,oop,Javascript,Php,Oop,我使用此标准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
/**
* 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类?您可以实现一些更通用的index.php,它自动实例化从某个抽象类继承的类,或者实现一个接口,即 然后可以将请求的类名作为参数或路径传递 但这并不是完全通用的,也不是自动的,它只是能够执行您的应用程序 您必须注意很多安全问题,以防止人们加载和实例化任意类
这个概念可能倾向于JSP中的servlet思想,您可能正在PHP中寻找它。是什么让您认为PHP不会自动创建RoadTaxDataParser类的实例?@Bjorn其中有一个文件。install.php和类所在的文件。@Bjorn根据我对OPs问题的理解,他想省略返回的新RoadTaxDataParser$road\u tax\u数据;我不知道你在想什么,但是你不能通过网络发送一个PHP对象并从JavaScript中使用它。您的脚本必须打印JavaScript可以解析JSON的内容。@AxelAmthor。