简体   繁体   中英

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.

$(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. It's normal that when you alert something like an object or an array it outputs that.

alert(JSON.stringify(data));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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