I am learning to build a simple API, I have the following code creating the following json:
Code:
$sql = "SELECT * FROM posts WHERE `user_id` = '$user_id' AND post_date > CURDATE() - INTERVAL 2 YEAR ORDER BY post_date DESC ";
$result = $dbc->query($sql);
$rows = array();
while ($row = mysqli_fetch_array($result))
{
$rows["posts"][$row['post_date']] = $row['post_content'];
}
echo json_encode($rows);
JSON created:
{"posts":{"2015-03-03":"33","2014-03-03":"33 33"}}
How do I parse this? I know the following code is a good start, but have not been able to go anywhere from there with success:
$.ajax({
url : "http://localhost:8888/290_project/api_write.php",
dataType: 'json',
type: 'get',
cache: false,
success : function(data){
}
});
Maybe I should then do something like in this w3 schools example?
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
I have yet to have luck thus far with this though, but I know I am so close!
To have a clearer interface to interact with, you may consider changing your script to return data in a form that is easier to work with:
while ($row = mysqli_fetch_array($result))
{
$post = array();
$post['date'] = $row['post_date'];
$post['content'] = $row['post_content'];
$rows["posts"][] = $post;
}
In your success function, you have access to the data as a javascript object
success : function(data){
alert(data.posts[0].date);
alert(data.posts[0].content);
}
You can manipulate this data here any way you like without parsing it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments