gpt4 book ai didi

jquery - 如何从 JQuery getJSON 读取数据

转载 作者:行者123 更新时间:2023-12-01 05:00:25 24 4
gpt4 key购买 nike

我正在努力解决 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 和 .secondcomplete)

我已经使用 Firebug 对此进行了调试,我可以看到我可以检索该对象,但我看到了 XML 错误

XML Parsing Error: syntax error Location: moz-nullprincipal:{0daef08f-94bc-4bea-879f-6456e8175e38} Line Number 1, Column 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 的各种选项,但似乎不起作用。

最佳答案

我认为您正在寻找更像这样的东西......尝试:

$(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 ...
});
});

关于jquery - 如何从 JQuery getJSON 读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10709241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com