无法使用来自ajax响应文本的Json数据

时间:2018-05-20 10:30:50

标签: javascript php json ajax

我正在使用javascript从ajax中获取数据库中的数据。答复文本如下:

{"task":"r","category":"s","duration":"0"}{"task":"read","category":"s","duration":"10"}{"task":"read","category":"o","duration":"10"}

我在php脚本上使用了json_encode($data),该脚本从MySql数据库中获取数据。如何将响应文本的任务,类别和持续时间存储在单独的变量中。我无法使用获得的回复。这是代码:

 if (mysqli_query($conn,$query)){
    $result = mysqli_query($conn,$query);
    $tasks = mysqli_fetch_all($result,MYSQLI_ASSOC);
    foreach($tasks as $task){
        echo json_encode($task);
    }
    mysqli_free_result($result);
}



 get(url){
    let xhr = new XMLHttpRequest();
    xhr.open('GET',url,true)
    xhr.onload= function(){
        if (this.status===200){
            let data = this.responseText;
            console.log(data);
        }
    }
    xhr.send();
}




2 个答案:

答案 0 :(得分:0)

如问题所述,您的回复不是正确的JSON格式。您的回复格式为:

{"task":"r","category":"s","duration":"0"}{"task":"read","category":"s","duration":"10"}{"task":"read","category":"o","duration":"10"}

有效的JSON响应应采用格式

[{"task":"r","category":"s","duration":"0"},{"task":"read","category":"s","duration":"10"},{"task":"read","category":"o","duration":"10"}]

一旦格式正确,用json_decode函数解码JSON并在循环中使用响应。

请参阅下面的示例以了解正确的解码:

$str = '[{"task":"r","category":"s","duration":"0"},{"task":"read","category":"s","duration":"10"},{"task":"read","category":"o","duration":"10"}]';

$response = json_decode($str, true);

foreach ($response as $res) {
   echo $res['task'] . ' ==== ' . $res['category'] . ' ===== ' . $res['duration'];
}

希望这有帮助。

答案 1 :(得分:-1)

尝试使用 dataType声明接收的数据类型:" json"

像这样:



[{"task":"r","category":"s","duration":"0"}, 
{"task":"read","category":"s","duration":"10"}, 
{"task":"read","category":"o","duration":"10"}]




此外,您的数据应该是单个json数组,而不是多个json对象

试试这个:

{{1}}

你应该在console.log

上有这样的输出
{{1}}