简体   繁体   English

将ajax与数据类型json一起使用

[英]Using ajax with datatype json

$query = "SELECT Subjects FROM instructors";
$rows = mysqli_query($con,$query);
{
    if($rows)
    {
        $count = 0;
        while($row = mysqli_fetch_array($rows))
        {
            $id = 'Name'.strval($count);
            // array_push($results,$row);
            $results[] = array($id => $row['Subjects']);
            $count = $count + 1;
        }
        echo json_encode($results);
    }
    else
    {
        echo "Something wrong";
    }
}

This outputs 这个输出

[{"Name0":"lore"},{"Name1":"ipsum"}]

Now in JS, I would like to get these names. 现在在JS中,我想获得这些名称。

$(document).ready(function(){
$.ajax({
 url: "get_subs.php",
 dataType :"JSON",
 success : function(data)
 {
    alert(data);
 }
    })
});

But this only prints 但这只打印

0 => [object Object]

I also tried 我也试过

alert(data.Name0);

But that also alerts the same thing. 但这也提醒了同样的事情。 What am I doing wrong? 我究竟做错了什么?

数据是一个数组,因此您需要按索引访问它:

alert(data[0].Name0);

Try JSON.stringify and see what it outputs. 尝试JSON.stringify并查看其输出。 It's normal that when you alert something like an object or an array it outputs that. 通常,当您警告类似对象或数组的东西时,它会输出该信息。

alert(JSON.stringify(data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM