Reputation: 46859
I could use another set of eyes - perhaps I am missing somehting obvious. I wrote a WCF service to return some basic data from my sql server database. It seems to function just fine. Now I am simply trying to dump that data to my webpage like this:
<script type="text/javascript">
$.ajax({ url: 'http://localhost:35798/restserviceimpl.svc/json/999?callback=?',
dataType: "jsonp",
success: function (data) {
alert(data);
$.each(data, function (i, item) {
$('#gallery').append('<p>' + i + '.'+ item + '</p>');
});
}
});
</script>
Using fiddler, it looks to me like correctly format json data is being returned to my webpage (and the alert shows me what looks json data which validates on jsonlint.com), but when I try to iterate over it I simply get one character for each 'each', instead of 'records'. I get 800+ iterations, each containing just one character of the JSON string, instead of the approximate 17 'records' of json data, each with two fields.
So am I getting a string back from my WCF that just 'looks like' JSON, or is my jquery script above have a bug?
Upvotes: 1
Views: 561
Reputation: 46859
Well, took me almost 2 days of trial an error, not sure if I had the problem on the WCF end or the jQuery end, but this is what I ended up with and works:
<script type="text/javascript">
$(function () {
$.ajax({
url: 'http://localhost:35798/restserviceimpl.svc/json/999',
type: 'GET',
dataType: 'jsonp',
success: function (data) {
var obj = $.parseJSON(data);
$.each(obj, function (i, item) { $('#gallery').append('<p>' + item.Id + '.' + item.Name + '</p>'); });
}
});
});
for some reason, which I don't fully understand, I had to add the $.parseJSON(data) line in order to convert the 'JSONP' string that was coming down from my WCF service, into useable JSON in order to be able to iterate over it. It is odd, because I consume JSONP from other places in this app, and didn't have to do this, so it is possible my WCF is sending slightly malformed results, that I need to compensate for in my jQuery, but until I figure out if that is true I am just going to go with what works.
Upvotes: 0
Reputation: 13139
Generally the script looks good.
Upvotes: 1