user2268887
user2268887

Reputation: 3

Use JavaScript to display data from JSONP web service

I'm trying to retrieve data from the itis.gov web service and display on an html page.

The site has JSON and JSONP web services. I cannot figure out why my code below is not working, I've got the code to work with other JSON web service APIs such as the facebook API.

Here is an example JSON API call using the webservice method "getScientificNameFromTSN"

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<script>
$(document).ready(function() {
   var url="http://www.itis.gov/ITISWebService/jsonservice/getScientificNameFromTSN?";
   $.getJSON(url, { "tsn" : "202384" }, function(data) {
      document.write(data.author);
   });
});
</script>
</head>
<body>
</body>
</html>

Upvotes: 0

Views: 1565

Answers (2)

Tommi
Tommi

Reputation: 3247

To support real ajax requests your server should answer with Access-Control-Allow-Origin: * header, but it does not.

Alternatively you can use $.ajax; it looks more clear and handy for me

$.ajax({
    url     : "http://www.itis.gov/ITISWebService/jsonservice/getScientificNameFromTSN",
    data    : { "tsn" : "202384" },
    dataType: "jsonp",
    jsonp   : "jsonp",
    success : function(data) { console.info(data); } 
});

Note that you should pass dataType to say jquery you query data cross-domain with padding and also you should provide query string parameter with callback name, as your server required (jsonp : "jsonp").

Result is

author: "Merriam, 1914"
class: "gov.usgs.itis.itis_service.data.SvcScientificName"
combinedName: "Ursus arctos nelsoni"
kingdom: "Animalia"
tsn: "202384"
unitInd1: null
unitInd2: null
unitInd3: null
unitInd4: null
unitName1: "Ursus"
unitName2: "arctos"
unitName3: "nelsoni"
unitName4: null

Upvotes: 0

alnorth29
alnorth29

Reputation: 3602

The documentation page that you link to contains this text:

JSON-P calls are made are made by appending "jsonp=function_name" to the argument list for your web service call.

For this to work with jQuery you'd need to add jsonp=? to the query string of your URL. For example:

$(document).ready(function() {
    var url="http://www.itis.gov/ITISWebService/jsonservice/getScientificNameFromTSN?jsonp=?";
    $.getJSON(url, { "tsn" : "202384" }, function(data) {
        document.write(data.author);
    });
});

jQuery will then replace the ? with the name of its automatically generated function.

Upvotes: 1

Related Questions