dongsheng1238 2017-02-14 19:18
浏览 78

我如何正确使用json ajax

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条回答 默认 最新

  • dongyue0225 2017-02-14 20:23
    关注

    You don't need to call JSON.stringify on the data that gets returned in your response. This method is for converting a javascript object to a JSON string, but your PHP code should be sending a JSON string back already by the looks of it.

    So it depends on what your returned JSON looks like, but usually it'll be something like this:

    {"name":"Mike", "phone":"5551234", ...} etc
    

    So in your success callback, you would do something like this:

    $("#name").text(data.name);
    $("#phone").text(data.phone);
    

    And so on.

    Note that I'm using the .text() method. You could use .html() as you've done but you probably don't need to unless your JSON strings contain HTML or you want to write out HTML like so:

    $("#name").html("<p>" + data.name + "</p>");
    

    As for styling, I would setup your styles in advance so that you don't have to do it in javascript as this will be more performant.

    However, if for some reason you needed to then you could do something like:

    $("#name").css({"display":block","color": "#000"});
    

    Hope that helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用