2012-05-26 121 views
1

我想使用JQuery的JSONP功能从网站检索气压数据。从JSON文件检索数据

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

另请参阅IBM提供的this article。在你的代码

+0

* * 1。)**您必须在JSFiddle中选择jQuery,而不是(默认)Mootools。 ** 2)**打开浏览器的JavaScript控制台,查看发生的错误。 ** 3。)**您尚未定义回调函数! – ComFreek

+0

我在第一个链接上得到了404。该页面未找到 – KeatsKelleher

+0

@akellehe他还在链接中忘记了“http://”。 – ComFreek

回答

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()返回两个parametersdata对象之内。

 - 1st one is `count` that have integer value 
    - 2nd one is `value`, which is an `Object`. 

为了得到第二个参数你需要使用data.value

DEMO

+0

对不起,我没有萤火虫。添加console.log有什么意义?在你的演示中,点击div仍然没有提示警报。谢谢 – Ian

+0

@Ian如果你打算开发JS开发,我认为强烈建议学习Firebug或者如何使用其他浏览器的JavaScript控制台。 http://stackoverflow.com/questions/55633/where-is-the-console-api-for-webkit-safari – KeatsKelleher

+0

@ Ian我用'alert()'做了我的小提琴,但你应该用来学习萤火虫 – thecodeparadox

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