2014-12-27 60 views
0

我使用这个(标准)JavaScript函数调用一个PHP文件,将数据发送给它:Automatticly实例PHP类JavaScript的HTTP请求

/** 
* 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类?

+1

是什么让你觉得PHP不会自动创建'RoadTaxDataParser'类的实例? – Bjorn 2014-12-27 19:01:46

+0

@Bjorn之间有一个文件。 'install.php'和类所在的文件 – Bas 2014-12-27 19:02:21

+0

@Bjorn据我了解OPs问题,他希望**省略**返回新的RoadTaxDataParser($ road_tax_data);'并且有一种auto-按请求加载。 – 2014-12-27 19:04:01

回答

0

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

的接口类。然后你可以通过请求的类名或者作为参数或者作为路径。

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

而且你必须关心很多安全问题,以防止人们加载和实例化任意(有害)的类。

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