I am struggling with getJSON. I have a simple StockWatcher application which returns the data in JSON format
http://localhost:8080/StockWatcherServer/stockwatcher/stockPrices?q=ABC+DEF+PQR
Output:
({
"stocks": [{
"symbol": "ABC",
"price": 80.11611442288577,
"change": 1.4332410131550721
}, {
"symbol": "DEF",
"price": 89.47611015580729,
"change": -1.469336678470048
}, {
"symbol": "PQR",
"price": 99.60017237722221,
"change": -1.3303545392913447
}]
})
When I use a simple Javascript function to read this, I get a Error (.error, .complete and .second complete)
I have used Firebug to debug this, and I can see that I can retrieve the object but I see a XML error
XML Parsing Error: syntax error Location: moz-nullprincipal:{0daef08f-94bc-4bea-879f-6456e8175e38} Line Number 1, Column 1:
({"stocks": [ ^
Here is the Javascript.
<script type="text/javascript">
$(document).ready(function(){
var url='http://localhost:8080/StockWatcherServer/stockwatcher/stockPrices?q=';
var query;
$('button').click(function(){
query=$("#query").val();
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON(url, function(data) {
var obj = $.parseJSON(data);
$.each(obj,function(i,item){
$("#results").append('Title:'+item.symbol+' == Price:'+item.price+'</p>');
});
})
.success(function(data) { alert("second success"); })
.error(function(data) { alert("error"); })
.complete(function(data) { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
});
});
</script>
I have experimented with various options calling parseJSON and without parseJSON,
but seems it doesn’t work.
I think you are looking for something more like this… Try: