我有一个php文件(todo.php & todo.js),它收集用户的一些数据并使用ajax发布收集数据到另一个PHP文件(add.php)被添加到数据库。我的问题是,我不想使用ajax将数据发布到第二个php文件(add.php)。我该如何改变这一点。我已提取的代码和下面如何将数据从一个php文件发布到另一个php文件,并将数据添加到数据库而不使用ajax
//todo.js所示从todo.php称为验证新todoEntry
function addToDo(){
var descField = document.getElementById('nDesc');
var percField = document.getElementById('nPerc');
if(!validateField(descField)){
alert("Description " + errorMessage);
return;
}
if(!validatePercentField(percField)){
alert("Percentage " + errorMessage);
return;
}
//use ajax to post new entries to add.php which will add them
ajaxCall(encodeURI('add.php?description=' + descField.value
+ '&percentage=' + percField.value), function(response){
if(response.status == 200){
if(response.responseText.toString().indexOf
("success") != -1){
//clear values
descField.value = "";
percField.value = "";
//refresh table
fetchToDo();
}
else
alert(response.responseText);
}
});
}
From add.php:
<?php
session_start();
if(!isset($_SESSION['username'])){
die("Your Session has expired. Please re-login to continue");
}
//get required data
$description = trim(isset($_GET['description']) ? urldecode($_GET
['description']) : "");
$percentage = trim(isset($_GET['percentage']) ? urldecode($_GET
['percentage']) : "");
//validate data
if(empty($description) || empty($percentage)){
die("All fields are required!");
}
//connect to database
include('connect.php');
//insert data
$stmt = $mysqli->prepare("INSERT INTO todo_entry VALUES (NULL, ?, NOW
(), NOW(), ?, ?)");
$stmt->bind_param("ssi", $_SESSION['username'], $description,
$percentage);
$stmt->execute();
if($stmt->affected_rows > 0){
$stmt->close();
echo "success";
}
else{
echo "An Error Occured: " . $stmt->error;
$stmt->close();
}
//close database
$mysqli->close();
?>
创建一个窗体,为第二页和method = post创建操作。您将在$ _POST的第二页获取所有数据。 –
这个逻辑有一个严重的缺点。事实上,你正在谈论你100%知道的非常基本的话题。你在说什么是表单功能。正如@anantkumarsingh所说的那样。生活比你想要的工作流程更容易。 – SaidbakR
是的,如果您不想使用表单加载另一个页面,那么Ajax是唯一的选择。 – Capsule