我正在努力使用getJSON。我有一个简单的StockWatcher应用程序,它以JSON格式返回数据
http://localhost:8080/StockWatcherServer/stockwatcher/stockPrices?q=ABC+DEF+PQR
输出:
({
"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
}]
})
当我使用一个简单的Javascript函数来读取它时,我得到一个错误(.error,.complete和.second complete)
我使用Firebug来调试它,我可以看到我可以检索对象,但是我看到了XML错误
XML解析错误:语法错误位置:moz-nullprincipal:{0daef08f-94bc-4bea-879f-6456e8175e38}第1行,第1列:
({"stocks": [ ^
这是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>
我已尝试过调用parseJSON且没有parseJSON的各种选项, 但似乎它不起作用。
答案 0 :(得分:1)
我认为你正在寻找更像这样的东西......试试:
$(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
$.ajax({
url : url,
type: "GET",
dataType: "json",
success: function(data) {
$.each(data.stocks,function(i,item){
$("#results").append('Title:'+item.symbol+' == Price:'+item.price+'</p>');
});
},
error: function(data) { alert("error"); },
});
// perform other work here ...
});
});
答案 1 :(得分:0)
如果您在原始JSON中使用“(”和“)”,请尝试以下操作:
{
"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
}
]
}