What is JSON and how do I create JSON objects?
The only thing you should know is that JSON is actually Javascript code. You can create arrays and objects with values, such as strings and numbers (as well as arrays and objects)
, , :
[12, "string", -30] // This is an array with 3 values
, , , :
{"key1": "value1", "key2": 234} // This is an object with two pair of keys and values
, . , , , JSON :
{
"key1": 12,
"key2": [
10,
"value"
]
}
JSON?
JSON , , API Twitter.
JSON Javascript AJAX. jQuery , JSON-. PHP JSON PHP.
Javascript:
someArray[0];
someObject.key;
, flickr:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
var firstImg = data.items[0];
$("<img/>").attr("src", firstImg.media.m).appendTo('body');
}
);
PHP :
$contents = file_get_contents('http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?');
$flickrStream = json_decode($contents);
echo '<img src="' . $flickrStream->items[0]->media->m . '" />';
:
AJAX, , . ... - , - .
$.ajax({
url: '/to/your/php/file/',
dataType: 'json',
data: {
"name": "client"
},
success: function(data){
alert(data.messageFromServer);
}
});
PHP ( , )
<?php
echo '{
"messageFromServer": "Hi back, ' . $_GET['name'] . '"
}';
?>