我希望能够通过点击按钮来调用特定的PHP函数
现在我有一段代码:
<table class='standardtable'>
<tr>
<th>Event</th>
<th>Group</th>
<th>Course</th>
<th>Due Date</th>
<th>Due In/<span class='red'>Late By</span></th>
</tr>
<?php
echo $html->tableCells($evalUpcoming);
?>
<?php if (empty($evalUpcoming)):?>
<tr><td colspan="5" align="center"><b> No peer evaluations due at this time </b></td></tr>
<?php endif; ?>
我想这样做,我可以创建两个按钮,正向和反向,单击正向按钮可以用evalUpcoming填充表格单元格,而单击反向按钮则用evalRevUpcoming填满表格单元格。
基于这篇文章:如何在点击按钮时调用PHP函数
以下是我迄今为止所尝试的:
<table class='standardtable'>
<tr>
<th>Event</th>
<th>Group</th>
<th>Course</th>
<th>Due Date</th>
<th>Due In/<span class='red'>Late By</span></th>
<input type="submit" class="button" name="forward" value="forward" />
<input type="submit" class="button" name="reverse" value="reverse" />
</tr>
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'forward':
forward();
break;
case 'reverse':
reverse();
break;
}
}
function forward() {
echo $html->tableCells($evalUpcoming);
exit;
}
function reverse() {
echo $html->tableCells($evalRevupcoming);
exit;
}
?>
<?php
echo $html->tableCells($evalUpcoming);
?>
<?php if (empty($evalUpcoming)):?>
<tr><td colspan="5" align="center"><b> No peer evaluations due at this time </b></td></tr>
<?php endif; ?>
然而,它似乎什么都没做,我甚至没有得到关于行动成功执行的警报。有人能告诉我我做错了什么吗?
此外,就我打算这样做的方式而言,这会导致表的内容立即更改吗?我不太熟悉PHP和HTML,所以我不确定当调用新的PHP代码时页面是如何变化的。
我想知道是否有一种更简单的方法可以做到这一点,我知道php代码以前已经加载过,但由于它只是填充一个html表,这不能在html中完成吗?
尝试如下转换按钮单击代码,可能会导致问题,因为它在表中。
$( ".standardtable tbody tr .button" ).on( "click", function() {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
首先使用e.preventDefault();
来防止表单提交的默认事件发生,然后将所有php移动到另一个文件,最后将ajax移动到该文件
$(document).ready(function(){
$('.button').click(function(e){
e.preventDefault();
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
},'html');
});
});
您的ajax.php文件应该如下所示:
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'forward':
forward();
break;
case 'select':
reverse();
break;
}
}
function forward() {
echo $html->tableCells($evalUpcoming);
exit;
}
function reverse() {
echo $html->tableCells($evalRevupcoming);
exit;
}
?>