我正在尝试访问并显示页面上 json 对象内的变量。谁能告诉我为什么变量显示三次?
my_array.php
<?php
$my_data=array(name=>"john",age=>"30", city=>"copenhagen");
// sending output
header('Content-Type: text/json');
echo json_encode($my_data,true);
?>
My_page.php
<script>
$(document).ready(function() {
$("button").click(function() {
$.getJSON("my_array.php", function(data) {
$.each(data, function(key) {
$("#showdata").append(data.city);
});
});
});
});
</script>
//Show the data further down the page.
<div id="showdata"></div>
这会显示
copenhagencopenhagencopenhagen
最佳答案
这是因为您正在迭代收到的 json 响应中的“每个”数据项,并且 my_array.php 中有 3 个键=>值对
删除“$.each(data, function(key) {}”将仅返回值“city”一次
$(document).ready(function(){
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});
});
关于javascript - 在 JSON 数组中回显变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36118175/