我正在尝试使用 JQuery 的 JSONP 功能从网站检索气压数据。
首先,我使用雅虎!用于将 XML 数据转换为 JSON 的管道。然后我尝试在警报中接收和使用该数据,但没有成功。在这个JSFiddle中,我有一个简单的工作示例,但是当我尝试使用更高级的 JSON 文件时,它不起作用。
另请参阅IBM 的这篇文章。
代码中的问题
http://
在您的链接中你需要试试这个(见alert
。它会提醒标题)
<div onClick="$.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=467a55b506ba06b9ca364b1403880b65&_render=json&textinput1=40.78158&textinput2=-73.96648&_callback=?', function(data){alert(data.value.title)})">Click Me</div><!--I can't get this to work-->
但它更好地使用如下:
<div class="loadjson">Click Me</div>
function barometer() {
$.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=467a55b506ba06b9ca364b1403880b65&_render=json&textinput1=40.78158&textinput2=-73.96648&_callback=?', function(data) {
alert(data.value.title);
})
}
$('div.loadjson').on('click', function() {
barometer();
});
注意: 在对象内$.getJSON()
返回两个。parameters
data
- 1st one is `count` that have integer value
- 2nd one is `value`, which is an `Object`.
要获得第二个参数,您需要使用data.value
.
我修复的代码有很多很多问题,并在线评论了这些问题......
jsfiddle在这里:http: //jsfiddle.net/kritzikratzi/LQcVd/
function loadBarometerData(){
// 1. it's not generally bad practice to put stuff in the
// onClick listeners, but really... don't put such long code there! it's not readable ...
// 2. you were missing a "http://" and it was downloading
// jsfiddle.net/pipes.yahoo.com/....
// 3. getJSON doesn't return a result immediately, you need to use callbacks for that!!
$.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=467a55b506ba06b9ca364b1403880b65&_render=json&textinput1=40.78158&textinput2=-73.96648&_callback=?' ).success( barometer );
};
function barometer(data) {
console.log( data );
// 4. you had items instead of items[0]
// similar with data.
alert(data.value.items[0].data[1].parameters.pressure.value);
};
function showPrice(data) {
alert("Symbol: " + data.symbol[0] + ", Price: " + data.price);
}