Reputation: 137
I want the PHP script to return the data in JSON format to the jquery
<?php
$json = array();
$json[] = array(
'id'=>1,
'username'=>'Administrator',
'session'=>'251981564887'
);
echo json_encode($json);
?>
Getting JSON object by calling PHP script
[
{
'id':1,
'username':'Administrator',
'session':'251981564887',
}
]
Parse this JSON query using jQuery $.get()
$.get('json.php', function(json) {
$data = json.replace('[', '');
$data = $data.replace(']', '');
$data = $.parseJSON($data);
console.log('ID: '+$data.id);
console.log('Username: '+$data.username);
console.log('Session: '+$data.session);
});
Everything is fine...
How to creating custom function to parse JSON data (real simple)?
$.get('json.php', function(json) {
$id = json.function_json('id');
$username = json.function_json('username');
$session = json.function_json('session');
console.log('ID: '+$id);
console.log('Username: '+$username);
console.log('Session: '+$session);
});
Any help would be great!
Upvotes: 0
Views: 148
Reputation: 337580
Use getJSON()
, that way it is already decoded for you.
$.getJSON('json.php', function(json) {
$.each(json[0], function(key, value) {
console.log(key + ': ' + value);
});
});
Upvotes: 1
Reputation: 7618
Specify the datatype
when you call your $.get()
function so that JQuery parses it for you automagically (source):
jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] );
Adapted example:
$.get('json.php', function(json) { /* Your function */}, 'json');
Default value:
Default: Intelligent Guess (xml, json, script, or html).
Upvotes: 0
Reputation: 7442
In jQuery you can use $.parseJSON
var j = $.parseJSON(json);
then get value as j.username
etc
Upvotes: 1