开发者

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?

Th开发者_Go百科anks 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜