I am new programmer and still learning.
I know the concept of Json(http://www.json.org/), but I am confused about under what situation that we should use CJson. Please let me know your opinion.
Also some examples CJson on Yii would be very helpfu!
I am new programmer and still learning.
I know the concept of Json(http://www.json.org/), but I am confused about under what situation that we should use CJson. Please let me know your opinion.
Also some examples CJson on Yii would be very helpfu!
I use mostly as ajax responses
something like:
//controller
if(Yii::app()->request->isAjaxRequest){
echo CJSON::encode(array(
'message'=>'User added',
));
}else{
//...
}
//js function to handle the json response
function(response){
if(response.message){
$("#my_message_field").html(response.message);
}
if(response.redirect){
window.location=response.redirect;
}
//...more usage cases here
}
something like that
JSON is a subset of javascript so javascript understand it.
Using jquery you can call a page like so:
$.ajax({
url: 'path/to/json.php',
dataType: 'json',
data: {
varName: 'varValue'
},
success: function () {
alert('page loaded!!!');
}
});
path/to/json.php can be a php page that use json_endode to represent some data like an array o php object in json way:
php array
$var = array('hello'=>'world');
echo json_encode($var);
would be:
{hello:'world'}
json is javascript. Is useful because of the result that you get is already readable from javascript:
$.ajax({
url: 'path/to/json.php',
dataType: 'json',
data: {
varName: 'varValue'
},
success: function () {
alert(hello); // it will print "world"
}
});
You can use json to rapidly send or get vars from or to server.
You could also use it to save a data array or multiple values in a database field (also human readable)
like
varDB = CJSON::encode(var);
and
var = CJSON::decode(varDB);