所以在一个文件中我有一个你在数据库中添加的形式,另一种形式是你检索的,另一种形式是你更新的.所有表单都使用javascript(ajax)向一些PHP文件发送信息.
例如:
//添加数据
function get(str) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxget.PHP?q=" + str, true);
xmlhttp.send();
}
//更新数据
function update() {
var ud_id = $('.ud_id').attr('value');
var ud_first = $('.ud_first').attr('value');
var ud_last = $('.ud_last').attr('value');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.PHP?ud_id=" + ud_id + "&ud_first=" + ud_first + "&ud_last=" + ud_last , true);
xmlhttp.send();
return false;
}
//添加新数据
function add() {
var add_ud_first = $('.add_ud_first').attr('value');
var add_ud_last = $('.add_ud_last').attr('value');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxadd.PHP?add_ud_first=" + add_ud_first + "&add_ud_last=" + add_ud_last , true);
xmlhttp.send();
return false;
}
正如您所看到的,所有片段都相应地发送到ajaxget.PHP,ajaxupdate.PHP和ajaxadd.PHP.我可以组合这些文件,所以我有1个PHP由所有片段调用?
因此,例如,所有片段都将调用ajax.PHP文件并在该文件中,如果get()调用它,则相应地执行.
那有意义吗?
<?PHP include("connection.PHP");
$q=$_GET["q"];
$query="SELECT * FROM contacts WHERE id = '".$q."'";
$result = MysqL_query($query);
while($row = MysqL_fetch_array($result))
{
echo "Name: " . $row['first'] . " <br />";
echo "Surname: " . $row['last'] . " <br />";
}
MysqL_close();
?>
解决方法:
在请求中添加一个参数(POST或GET)以确定它的请求类型.
例如,如果您发送GET参数(?operation = insert),那么在PHP代码中您应该使用switch / if-else来执行正确的代码.
$allowed_operations = array('insert', 'update', 'delete');
if( isset($_GET['operation'])
&& in_array(isset($_GET['operation']), $allowed_operations)){
switch($_GET['operation']){
case 'insert':
// do insert operation here
break;
case 'update':
// do update operation here
break;
case 'delete':
//do delete operation here
break;
}
}
编辑1
>将ajaxget.PHP,ajaxupdate.PHP和ajaxadd.PHP的所有代码放在ajaxop.PHP或其他任何内容中.
>将ajaxget.PHP内容保存在函数ajax_get()中,对其他函数保持相同.
>更改xmlhttp.open以便它只调用ajaxop.PHP并在URI中添加operation = get,operation = update等根据您的需要.
>在switch语句中映射这些参数.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。