dongwu5801 2017-02-14 17:37
浏览 27
已采纳

我如何正确使用json

I want to send data from php to a browser using JSON. I think I understand the process - see my example code below. But someone told me this is not the right way to do it. I have been researching for three days but because my English is poor I am not confident that I have found an answer.

What I am hoping for is a sample of code that will receive the JSON and pour it into html elements such as a div, and give it style via CSS, etc.

I really just want an example of how to do this so that I can learn from it and expand it myself for my own needs, but I am unconfident that this approach is correct and do not want to write more bad code.

Thanks

Javascript

$(document).ready(function() {
    $.ajax({
        type : 'POST',
        url : 'server.php',
        dataType:"json",
        success : function (data) { 
            $("#orders").html(JSON.stringify(data));
        }
    }); 
});

PHP

<?php 
    $db = new PDO('mysql:host=localhost;dbname=Contact', 'root', '');
    $statement=$db->prepare("SELECT * FROM myfeilds");
    $statement->execute();
    $results=$statement->fetchAll(PDO::FETCH_ASSOC);
    $json=json_encode($results);
    echo $json;
?>
  • 写回答

1条回答 默认 最新

  • dozxos6346 2017-02-14 18:19
    关注
    $(document).ready(function() {
        $.ajax({
            type : 'POST',
            url : 'server.php',
            dataType:"application/json",
            success : function (data) { 
               var jsns=JSON.parse(data);
               $("#orders").html("");//clear the div
               for(var i in data)
               {
                 var id = data[i].id;
                 var name = data[i].name;
                 $("#orders").append("<span>"+id+"-"+name+</span>);//append each element
               }
            }
        }); 
    });
    

    Since your server side php is already returning json.. you can just loop through the array of objects after converting it into JSON and then do DOM manipulation.

    The best way to do it would be to use some templating engine like underscore.js

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码