简体   繁体   中英

How do I properly use the 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;
?>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM