javascript - 在 JSON 数组中回显变量

标签 javascript php jquery

我正在尝试访问并显示页面上 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/

相关文章:

javascript - 如何解析获取d3.js中的数据

javascript - 如何为我的 console.log 数据制作 key 并将其附加到 html(控制台日志结果到文本框)

javascript - MongoDB mongoose 弃用警告

javascript - javascript 可以处理的最大文件大小是多少?

javascript - jQuery 验证插件 : disable validation for specified submit buttons when there is submitHandler handler

php - 如何在sublime中使用phpcs来学习编码标准?

php - Netbeans - 创建 HTML 元素的自定义快捷方式

javascript - jQuery 没有在幻灯片容器 div 中加载元素

javascript - 使用 jquery 创建 Web 小部件并向其传递参数

javascript - 如何强制电子邮件验证在 webview android 中打开