我意识到从JavaScript文件调用数据库不是一个好方法.所以我有两个文件:
server.php有多个功能.根据条件,我想调用server.php的不同功能.我知道如何调用server.php,但是如何在该文件中调用不同的函数?
我当前的代码如下所示:
function getphp () {
//document.write("test");
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// data is received. Do whatever.
}
}
xmlhttp.open("GET","server.php?",true);
xmlhttp.send();
};
Run Code Online (Sandbox Code Playgroud)
我想做的是(只是伪代码.我需要实际的语法):
xmlhttp.open("GET","server.php?functionA?params",true);
Run Code Online (Sandbox Code Playgroud)
基于这个前提,你可以设计这样的东西:
在这样的示例请求上:
xmlhttp.open("GET","server.php?action=save",true);
Run Code Online (Sandbox Code Playgroud)
然后在PHP中:
if(isset($_GET['action'])) {
$action = $_GET['action'];
switch($action) {
case 'save':
saveSomething();
break;
case 'get':
getSomething();
break;
default:
// i do not know what that request is, throw an exception, can also be
break;
}
}
Run Code Online (Sandbox Code Playgroud)