从JSON文件中检索数据

时间:2012-05-26 14:15:17

标签: javascript jquery json jsonp yahoo-pipes

我正在尝试使用JQuery的JSONP功能从网站检索气压数据。

首先,我使用了雅虎!用于将XML数据转换为JSON的管道。然后我尝试在警报中接收并使用该数据,但它不起作用。在这个JSFiddle中,我有一个简单的工作示例,但是当我尝试使用更高级的JSON文件时,它不起作用。

另请参阅IBM的this article

2 个答案:

答案 0 :(得分:1)

代码中的问题

  • 您忘记在链接中加入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-->

<强> DEMO

但最好使用如下:

<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

<强> DEMO

答案 1 :(得分:1)

我的代码修复了很多很多问题并对内联问题进行了评论......

这里的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);
}
​