现在我有两种提交表单的方法——一种是启用 Javascript(ajax 表单提交,提交到 process.php),另一种是未启用 Javascript(提交到 index.php)。但是,现在我启用了 Javascript,并且 JQ/Ajax 提交不起作用,因为页面正在刷新。
索引.php:
<?php
include_once('TaskDB.php');
include_once('task.php');
// JAVASCRIPT DISABLED
if(isset($_POST['description_text']) && isset($_POST['deadline_text'])){
$description = $_POST['description_text'];
$duration = $_POST['duration_text'];
$deadline = $_POST['deadline_text'];
// create a new task object, add it to database
$task = new Task('DEFAULT', $description, $duration, $deadline, '0');
TaskDB::addTask($task);
// to prevent re-submission upon refreshing the page
header('Location: index.php');
}
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>Taskage</title>
<script>
$(document).ready(function(){
$('#task_form').submit(function(e){
$.post('process.php', $("#task_form").serialize(), function(data){
// clear the current task table
$('#form').nextAll('tr').empty();
// refresh the task table with the newly inserted task
$(data).insertAfter('#form');
});
e.preventDefault();
});
});
</script>
</head>
<body>
<div id="topframe">
<div id="logo"></div>
</div>
<div id="nav">
<table id = nav_table>
<tr>
<td><a href="index.php"><img src="images/tab1m.png" class="navimg" id="tab1"/></a></td>
<td><a href="completed.php"><img src="images/tab2.png" class="navimg" id="tab2"/></a></td>
<td><a href="failed.php"><img src="images/tab3.png" class="navimg" id="tab3"/></a></td>
<td><a href="settings.php"><img src="images/tab4.png" class="navimg" id="tab4"/></a></td>
</tr>
</table>
</div>
<div id="main_area">
<h2>Tasks</h2>
<table id = "tasks_table">
<tr>
<th>Date</th>
<th>Hours</th>
<th>Task</th>
<th></th>
</tr>
<tr id = "form">
<form action="index.php" method="POST" id="task_form">
<td><input type="text" id="deadline_text" name="deadline_text"/></td>
<td><input type="text" id="duration_text" name="duration_text"/></td>
<td><input type="text" id="description_text" name="description_text"/></td>
<td><input type="submit" value="Add Task" id="task_submit"/></td>
</form>
</tr>
<?php
TaskDB::generateTaskTable();
?>
</table>
</div>
</body>
</html>
进程.php:
<?php
include_once('TaskDB.php');
include_once('task.php');
if(isset($_POST['description_text']) && isset($_POST['deadline_text'])){
$description = $_POST['description_text'];
$duration = $_POST['duration_text'];
$deadline = $_POST['deadline_text'];
// create a new task object, add it to database
$task = new Task('DEFAULT', $description, $duration, $deadline, '0');
TaskDB::addTask($task);
TaskDB::generateTaskTable();
}
?>
每当提交表单时都有一个 preventDefault() ,所以我不知道为什么页面会刷新。任何帮助将不胜感激。谢谢。