简体   繁体   中英

JSONP request using jquery $.getJSON not working on well formed JSON

I'm not sure is it possible now from the url I am trying. Please see this url: http://www.heiaheia.com/voimakaksikko/stats.json

It always serves the same padding function "voimakaksikkoStats". It is well formed JSON, but I have not been able to load it from remote server. Does it need some work from the server side or can it be loaded with javascript? I think the problems gotta to have something to with that callback function...

JQuery is not requirement, but it would be nice.

This (callback=voimakaksikkoStats) returns nothing (firebug -> net -> response), and alert doesn't fire:

$.getJSON("http://www.heiaheia.com/voimakaksikko/stats.json?callback=voimakaksikkoStats", function(data){
    alert(data);
})

but this (callback=?):

 $.getJSON("http://www.heiaheia.com/voimakaksikko/stats.json?callback=?", function(data){
    alert(data);
})

returns:

voimakaksikkoStats({"Top5Sports":[],"Top5Tests":{"8":"No-exercise ennuste","1":"Painoindeksi","2":"Vy\u00f6t\u00e4r\u00f6n ymp\u00e4rys","10":"Cooperin testi","4":"Etunojapunnerrus"},"Top5CitiesByTests":[],"Top5CitiesByExercises":[],"ExercisesLogged":0,"Top5CitiesByUsers":[""],"TestsTaken":22,"RegisteredUsers":1});

But I cannot access it... In both examples the alert never fires. Can someone help?

<script type="text/javascript">
function voimakaksikkoStats(stats) {
  var ul = new Element('ul');
  ul.insert(new Element('li').update('Registered users: '+ stats['RegisteredUsers']));
  ul.insert(new Element('li').update('Tests taken: '+ stats['TestsTaken']));
  ul.insert(new Element('li').update('Top5 sports: '+ stats['Top5Sports'].join(', ')));
  $(document.body).insert({'bottom': ul});
}
</script>
<script type="text/javascript" src="http:/www.heiaheia.com/voimakaksikko/stats.json"></script>

This example uses Prototype.js to create list with some data from given stats, and then puts this list at the bottom of document body.

is the script trying to fetch json from http://www.heiaheia.com also on http://www.heiaheia.com ?

if not this is the cause, it's currently not authorized to make request (using javascript) to another server than the one serving the script

为了使您的测试功能正常工作,请尝试更改为callback=?

If the your request goes to anonther domain try using jsonP method. Search for jsonP docs

<script type="text/javascript">
function voimakaksikkoStats(obj) {
    alert(obj.TestsTaken);
}
</script>
<script type="text/javascript" src="http://www.heiaheia.com/voimakaksikko/stats.json"></script>

I never got it working with jQuery, but the simple code above solved my problems. I found help from Yahoo: http://developer.yahoo.com/common/json.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM