saveTask()
函数调用 requestJSONAJAX
,但 requestJSONAJAX
函数返回 false
。即使对我的 tasklog.php
的查询成功,也会发生这种情况;它甚至更新我的数据库。我不知道我的错误源自何处。是在我的 tasklog.php
中还是在 JavaScript 函数中,还是我使用的 return
错误?
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);
}
});
}
任务日志.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;
}
?>
最佳答案
您不会从 requestJSONAJAX
返回任何内容。您在 $.ajax()
调用中从 success
处理程序返回一个 bool 值,但这无关紧要。这并不会使包含 $.ajax()
调用的函数(即 requestJSONAJAX
)返回任何内容。
您似乎正在尝试根据 AJAX 调用的成功或失败从 requestJSONAJAX
返回一个值。这不可能;这就是为什么它被称为“AJAX”(异步 JavaScript 和 XML)。 requestJSONAJAX
将(本质上)始终在 AJAX 调用之前完成。即使它没有首先完成,它也不会等待 AJAX 调用,并且无法判断调用是成功还是失败。
要捕获调用是否成功,您需要在某处设置一个标志(例如全局变量)。更好的是,只需在成功处理程序中处理您想要执行的任何操作即可。不用担心返回值。
关于javascript - 为什么我的 ajax 函数返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43382682/