简体   繁体   中英

help with Jsonp and jQuery

I have a web service served in jsonp, but since I'm new to this I have difficulties retrieving the data. Here's my code:

$(document).ready(function(){               
   $.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=myData",
       function myData(result){
           $('#status').append(result.name.text);
        }
   );

});

the div #status returns empty.

could you help?

Thanks in advance

Mauro

Update: now it works! Bout it does't when I'm trying to loop though the data:

$.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?",
         function (result){
              $.each(result.items, function(item){
                 $('#status').append(item.response.lines[0].name);
        });
     }
);

What am I doing wrong?

Thanks

From jQuery API :

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.

I think your code should look something like this

$.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?", function (result){
    $('#status').append(result.name.text);
});

The trick is the json=? part of the URL. I think jQuery creates a function on the fly to parse de JSONp data and feeds the result to your callback function.

Excuse my English :)

Update: to access the data you must iterate over result.response.lines inside the callback function

$.each(result.response.lines, function() {
    $('#status').append(this.name);
}

This is the output of the URL:

myData({"response":{"lines":[{"name":"Central"},{"name":"Victoria"}]}});

You can reformat the object to make it clearer:

{
    "response": {
        "lines": [
            {"name":"Central"},
            {"name":"Victoria"}
        ]
    }
}

I see no property called text . You probably mean:

$('#status').append(result.response.lines[0].name);

Update: this solution doesn't fully solve the problem. As suggested in the accepted answer, you need to instruct jQuery to generate a random function name (you cannot provide your own, not at least with getJSON).

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