简体   繁体   中英

How do I access this associative array in javascript?

I have a php file where I am pulling data from a database and I want to access its contents in javascript. When I try to access the array with data[0].card_id I get "undefined".

Here is my javascript

$(document).ready(function() {
  var userId = 1;
  var updateUrl;

  $.ajax({
    type: "POST",
    url: "url",
    data: {userId: userId},
    success: function(data) {
      alert(data[0].card_id);
      var suffix = ".html";
      fb.start('../Animations/' + updateUrl[0].card_id + suffix); 
    }
  });
}

Here is my php file

<?php

include('connect.php');

$user_id = $_POST['userId'];

$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL";
}

$select = "SELECT card_id FROM decks WHERE id=$user_id ORDER BY order_num";
$result = mysqli_query($db, $select);

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
    $animation[] = array(
        'card_id' => $row['card_id'],
    );
}

json_encode($animation);
echo $animation;
mysqli_close($db);
?>

The array contains the following data

Array ( [0] => eating [1] => mummy

etc.. )

You have two problems.

First: You aren't doing anything with the return value of json_encode .

Second: The PHP is claiming it is sending back HTML, so it wouldn't parsed as JSON anyway.

header("Content-Type: application/json");
echo json_encode($animation);

You need to add dataType: "json" to your ajax call.

$.ajax({
    type: "POST",
    dataType: "json",
    url: "url",
    data: {userId: userId},
    success: function(data) {
        alert(data[0].card_id);
        var suffix = ".html";
        fb.start('../Animations/' + updateUrl[0].card_id + suffix); 
    }
});

http://api.jquery.com/jQuery.getJSON/

There is no need to change MIME type, jQuery will handle this.

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