我正在开发一个用于学习目的的小应用程序。
对于这个应用程序,我有一个 Mysql 数据库,其中每一行都是一个“任务”。每个任务都有一个“状态”字段,其中包括 id_task。当我单击按钮时,AJAX 调用会向 PHP 文件发送请求,在该文件中更新状态并检索结果。
状态的可能值为 NULL(默认)“DONE”和“REMOVE”。
我用它来创建包含所有任务的列表,根据状态,文本将显示为绿色(“完成”)、默认黑色(“NULL”)或不会显示(“删除”) 。
是的,我可以简单地删除“已删除”的任务,但我更喜欢将它们保留在数据库中,以防我希望用户能够恢复它们
当我创建的 php 函数具有以下 sql 查询时,一切正常:
public function retrieveDataByID($p_id_task)
{
$result="";
$arraySubjects=array();
$this->openConnection();
$sql="SELECT * FROM tareas where id_task=".$p_id_task;
$result=mysqli_query($this->connection, $sql);
if($result !=null)
{
while($fila=mysqli_fetch_assoc($result))
{
$arrayEditedSubjects[]=$fila;
}
}else{
//echo "no results";
}
$this->closeConnection();
return $arrayEditedSubjects;
}
但是当我想过滤查询以使状态为“REMOVE”的行不出现时,不会生成列表并且 AJAX 调用会抛出此错误:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
我不知道出了什么问题。这是有问题的查询的代码:
public function retrieveDataByID($p_id_task)
{
$result="";
$arraySubjects=array();
$this->openConnection();
$sql="SELECT * FROM tareas where (id_task=".$p_id_task.") AND (status <> 'REMOVE')";
$result=mysqli_query($this->connection, $sql);
if($result !=null)
{
while($fila=mysqli_fetch_assoc($result))
{
$arrayEditedSubjects[]=$fila;
}
}else{
//echo "no results";
}
$this->closeConnection();
return $arrayEditedSubjects;
}
这是抛出错误的 AJAX 调用,以防它可以帮助您:
$.ajax({
method:"post",
data:{'day_and_month':cellIDValue},
url:"assets/php/retrieve.php",
success:function(result){
let parsedResult=JSON.parse(result);
buildList("#subjectDiv",parsedResult);
},
error: function(xhr){
alert(xhr.status);
}
});
这是在 AJAX 函数上调用的 retrieve.php 文件
<?php
require_once('models/Connect.php');/*this is where the retrieveDataByID function is defined*/
$arrayJSONresults=array();
$objConexion=new Connection;
$arrayJSONresults= $objConexion->retrieveData($_POST['day_and_month']);
echo json_encode($arrayJSONresults);
?>
最佳答案
我通过以下查询修复了它:
$sql="SELECT * FROM tareas where (id_task=".$p_id_task.") AND ((status IS NULL) OR (status <> 'REMOVE'))";
由于默认状态为 NULL,我必须首先评估状态是否为 NULL(在其他情况下,我已阅读 SQL 引擎无法正确评估它)。
然后,如果它为 NULL,或不同于“REMOVE”(即 NULL 或“DONE”),它将显示在列表中。
也许我将默认状态设置为与 NULL 不同的值以避免这种情况,但我现在学到了一些新东西。
关于javascript - MySQL 查询在 PHP 中出现 JSON.parse 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49712516/