[英]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. 我有一个PHP文件,我从数据库中提取数据,我想在javascript中访问其内容。 When I try to access the array with data[0].card_id I get "undefined".
当我尝试使用data [0] .card_id访问数组时,我得到“未定义”。
Here is my javascript 这是我的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文件
<?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 数组([0] =>吃[1] =>木乃伊
etc.. ) 等..)
You have two problems. 你有两个问题。
First: You aren't doing anything with the return value of json_encode
. 第一:你没有对
json_encode
的返回值做任何事情。
Second: The PHP is claiming it is sending back HTML, so it wouldn't parsed as JSON anyway. 第二:PHP声称它正在发回HTML,因此无论如何它都不会被解析为JSON。
header("Content-Type: application/json");
echo json_encode($animation);
You need to add dataType: "json"
to your ajax call. 您需要将
dataType: "json"
添加到您的ajax调用中。
$.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/ http://api.jquery.com/jQuery.getJSON/
There is no need to change MIME type, jQuery will handle this. 没有必要更改MIME类型,jQuery将处理这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.