I need to parse a simple json response (from my rails app开发者_StackOverflow中文版):
[
{
"photo":
{
"updated_at":"2010-10-14T19:12:35Z",
"photo_file_size":206422,
"created_at":"2010-10-14T19:12:01Z"
}
},
{
"photo":
{
"updated_at":"2010-10-16T18:19:38Z",
"photo_file_size":83593,
"created_at":"2010-10-14T19:14:35Z"
}
}
]
i am using:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "http://myurl...",
dataType: "jsonp",
success: function(data){
console.log(data);
//...
});
}
});
});
firebug console output indicate that the response is ok!
How can i parse each photo_file_size from all photo blocks using function(data)?
any help will be highly appreciated :-)
jQuery will automatically parse the data as JSON, because you set the data type. In the success method you can use basic Javascript to do something with photo_file_size
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://myurl...",
dataType: "json",
success: function(data){
for( var i=0; i<data.length; i++ ){
alert( data[i].photo.photo_file_size );
}
}
});
});
However, if you're using JSONP, you need to approach it completely different. JSONP has a callback function, and will be served in a <script>
tag (to avoid the same origin policy, see Wiki)
<script>
function callback( data ){
for( var i=0; i<data.length; i++ ){
alert( data[i].photo.photo_file_size );
}
}
</script>
<script src="yoururltojsonp.php?callback=callback"></script>
Also, take a look at jQuery's solution
jQuery's JSON parser is $.parseJSON()
. So, in your success function:
var json = $.parseJSON(data);
or, if you weren't using a json response type:
var json = $.parseJSON(data.responseText);
and you should be good to go.
function(data)
{
for(var i=0; i<data.length; i++)
console.log(data[i].photo.photo_file_size);
}
This isn't JSONP data, this should just be JSON. Then you will have access to the data as if it were a normal variable. In this case, data would be an array.
This is assuming the server is the same as the server that is requesting the JSON.
If you need JSONP data it should look similar to this:
$callback$([
{
"photo":
{
"updated_at":"2010-10-14T19:12:35Z",
"photo_file_size":206422,
"created_at":"2010-10-14T19:12:01Z"
}
},
{
"photo":
{
"updated_at":"2010-10-16T18:19:38Z",
"photo_file_size":83593,
"created_at":"2010-10-14T19:14:35Z"
}
}
]);
$callback$ is just a simple print of whatever was passed in the callback= GET variable. In essence, JSONP is really just calling a function (callback). It's placed in the DOM as a script tag, which is why it circumvents the cross-domain issue. (Maybe that's too much information :)
精彩评论