使用JavaScript显示来自JSONP Web服务的数据

时间:2013-04-11 05:49:40

标签: javascript jquery json web-services jsonp

我正在尝试从itis.gov网络服务中检索数据并显示在html页面上。

该网站有JSON and JSONP web services。我无法弄清楚为什么我的代码无法正常工作,我已经获得了与其他JSON Web服务API(如facebook API)一起使用的代码。

以下是使用webservice方法“getScientificNameFromTSN”的示例JSON API call

<!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>

2 个答案:

答案 0 :(得分:1)

您链接到的文档页面包含以下文本:

  

通过将“jsonp = function_name”附加到您的Web服务调用的参数列表来进行JSON-P调用。

为了使用jQuery,您需要将jsonp=?添加到URL的查询字符串中。例如:

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

然后jQuery将?替换为其自动生成的函数的名称。

答案 1 :(得分:0)

要支持真正的ajax请求,您的服务器应该使用Access-Control-Allow-Origin: *标头回答,但它不会。

或者您可以使用$.ajax;它对我来说看起来更清晰,更方便

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

请注意,您应该传递d​​ataType来说明使用padding查询跨域数据的jquery,并且您应该提供带有回调名称的查询字符串参数,作为您的服务器所需(jsonp : "jsonp")。

结果是

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