Reputation: 5896
I am new on JQuery. I have this JSON response from the server how could I parse it?
[
{
"note": {
"created_at": "2012-04-28T09:41:37Z",
"updated_at": "2012-04-28T09:41:37Z",
"text": "aaaaaaaaaaafdafasd fasfasd dfa sdfasf asdfa fasdfda",
"lng": 44.5159794497071,
"id": 7,
"deleted": false,
"user_id": 1,
"note_type": "text",
"lat": 40.1884140543842
}
},
[ ... more JSON ...]
]
How could I parse this?
Upvotes: 0
Views: 388
Reputation: 19858
You have to set the data type of the request to "json", and the data will be already parsed in your success callback.
Everything you need to know at the moment is on http://api.jquery.com/jQuery.ajax/
Here is a very simple example of what you can do:
$.ajax({
url: url, // the service URL. Must answer proper JSON
data: { // the parameters of the request. This should be adapted to your case
param1: value1,
param2: value2
},
dataType: "json",
type: "POST",
success: function(resultData) {
// here, resultData is your parsed json
},
error: function() {
// handle error here
}
});
Upvotes: 3
Reputation: 10533
That's not JSON. What you have posted looks like a PHP array that had brackets wrapped around it to try to make it into JSON.
Use this site to validate your JSON in the future.
Now, to get your PHP array into JSON, use json_encode()
and dispatch it to the browser with a specific header.
$array = array( 'test' => 'sure' );
header('Content-type: application/json');
print json_encode($array);
exit;
Now, you'll have actual JSON with which you can use in JavaScript.
$.get( 'yourFile.php',
function(data){
console.log(data);
}
);
Upvotes: 0
Reputation: 944010
If the server outputs actual JSON (the example in the question has errors) and it has the correct content type (application/json
rather then the text/html
that PHP defaults to) then you don't need to do anything.
jQuery will parse it for you (and present you with a JavaScript object in the success handler).
Upvotes: 0