我的数据在mysql中。我正在使用PDO用php提取数据,然后使用json_encode转换为js。当我使用以下场景时,我总是得到输出NaN,如果我使用静态数组,它的工作原理。所以我猜它是错误的json格式或者是php的东西。
如果我顺利设置数组的值,这是有效的: codepen:http://codepen.io/pghiran/pen/QEvRjW
动态(从数据库中提取数据并存储在数组中,不起作用。我执行此操作的代码:
PHP
$exchangeRates = array();
$sql = 'SELECT * FROM exchange';
try {
$stmt = $conn->prepare($sql);
$stmt->execute();
for ($i=0; $row=$stmt->fetch();$i++){
$exchangeRates[] = array($row['rs3'],$row['07'],$row['deadman'],$row['currency']);
}
}catch(exception $e){
return $e;
}
var_dump($exchangeRates);
var_dump显示:array(1){[0] => array(4){[0] => string(3)“0.5”[1] => string(3)“1.5”[2] => string(3)“3.5”[3] => string(1)“$”}}
JS / Jquery的:
var amount = $('#amount'),
goldtype = $('#goldtype'),
exchange= <?php echo json_encode($exchangeRates);?>,
price = $('#price');
console.log(exchange);
goldtype.change(function () {
var exchangeIndex = $("select[name='goldtype'] option:selected").index();
price.val(amount.val() * exchange[exchangeIndex]);
})
console.log(exchange)显示:
[Array[4]]
0
:
Array[4]
0
:
"0.5"
1
:
"1.5"
2
:
"3.5"
3
:
"$"
length
:
4
答案 0 :(得分:1)
$exchangeRates[] = array($row['rs3'],$row['07'],$row['deadman'],$row['currency']);
仅在exchangeRates [0]中保存。我已将此行更改为:
$exchangeRate = array($row['rs3'],$row['07'],$row['deadman'],$row['currency']);