我是一名菜鸟PHP开发人员。
我已经创建了一个包含带有“添加”按钮的HTML页面的PHP
Web项目。该页面的名称是awards.html。awards.html文件包含其对应的JavaScript文件awards.js。单击添加按钮时,将在此js文件中执行代码。此代码将AJAX调用发送到位于/controller/名为Award.php的项目的文件夹中的PHP类。该PHP文件包含代码,该代码用于执行位于/model/项目文件夹中的另一个Award.php文件中名为addFunction()的函数,该文件返回JSON数组,并显示在awards.html页面中。
我的文件的源代码如下:
Awards.html
Add
awards.js
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
Award.php(位于/controller/文件夹中)
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
Award.php(位于/model/文件夹中)
class Award
{
public function addFunction() {
$array = array(
'status' => '1'
);
return $array;
}
}
我的代码运行完美且无错误。现在,我想在awards.html中添加另一个名为Save的按钮,单击该按钮将在JS文件中调用onSave()函数。因此,我文件的源代码将更改为以下内容:
awards.html
Add
Save
awards.js
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
function onSave() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
现在的问题是,由于我想从JS调用相同的Award.php文件,如何修改控制器的Award.php文件?我认为应该有两个不同的函数,其中应包含用于实例化Award.php类的视图并调用另一个函数的代码;类似于以下内容:
Award.php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
function add(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
}
function save(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->saveFunction();
echo json_encode($method);
}
Award.php
class Award
{
public function addFunction() {
$array = array(
'status' => '1'
);
return $array;
}
public function saveFunction() {
$array = array(
'status' => '2'
);
return $array;
}
}
但是,如何从JS文件中调用这些特定的PHP函数呢?如果我上面假设的代码正确,那么我的JS代码应该是什么?有人可以建议我吗?最早的答复将不胜感激。先感谢您。