saveTask()
函数调用requestJSONAJAX
,但requestJSONAJAX
函数返回false
。即使我的tasklog.php
上的查询成功,也会发生这种情况;它甚至更新我的数据库。我不知道我的错误来自哪里。是在我的tasklog.php
或JavaScript函数中,还是我在使用return
错误?为什么我的ajax函数返回false?
function saveTask(){
if(requestJSONAJAX('add')){
goSuccess();
}else{
alert('error');
}
}
function requestJSONAJAX(action){
var newObj;
if(action == "add"){
newObj = { action: "add",
date: $("#date").val(),
taskName: $("#taskName").val(),
taskType: $("#taskType").val(),
duration: $("#duration").val(),
startTime: $("#startTime").val(),
endTime: $("#endTime").val()
}
}else if(action == "login"){
newObj = { action: "login",
username: $("#username").val(),
password: $("#password").val()
}
}
$.ajax({
method: "POST",
url:"../_tasklogger/classes/tasklog.php", //the page containing php script
dataType: 'json',
data: newObj,
success: function(data){
status = data;
if(status == "success"){
return true;
}else{
return false;
}
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
});
}
tasklog.php
<?php
require_once 'dbconfig.php';
if(empty($_POST['action'])){
return;
}
if(($_POST['action']) != "getData"){
$date= $_POST['date'];
$taskName= $_POST['taskName'];
$taskType= $_POST['taskType'];
$duration= $_POST['duration'];
$startTime= $_POST['startTime'];
$endTime= $_POST['endTime'];
}
switch($_POST['action']){
case "add":
$sql = "INSERT INTO tasks (taskDate,taskName,taskType,duration,startTime,endTime,userId) VALUES(:tdate, :tname, :ttype, :dur, :stime, :etime, 1)";
$stmt = $db_con->prepare($sql);
$stmt->bindParam(":tdate", $date);
$stmt->bindParam(":tname", $taskName);
$stmt->bindParam(":ttype", $taskType);
$stmt->bindParam(":dur", $duration);
$stmt->bindParam(":stime", $startTime);
$stmt->bindParam(":etime", $endTime);
if($stmt->execute()){
echo json_encode("success");
}else{
echo json_encode("error");
}
break;
case "getData":
break;
case "delete":
/* .... some code .... */
break;
case "update":
/* some code ...
notice there is no "break" here... and execution continues to the next case.... falls-thru */
default:
return;
}
?>
我明白了。现在我明白为什么我的ajax函数不会返回值。感谢您提供丰富的回复,这对我刚开始学习Ajax的人来说是一个很大的帮助。谢谢! –