需要帮助调用API

时间:2016-04-18 02:36:44

标签: javascript ajax api http

我们正在尝试使用JavaScript调用API。 API的网站上有一个示例JavaScript,如下所示:

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(function() {
        var params = {
            // Request parameters
        };
      
        $.ajax({
            url: "https://emi.azure-api.net/ICPConnectionData/single/?id={ICP}&" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
            },
            type: "GET",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>

我们输入了{ICP}和{订阅密钥},但是当我们运行它时,我们每次都会收到错误。

我们得到的错误只是失败并显示警告(“错误”)的错误。我们尝试使用data.status并收到错误0“错误”。

Here's a screenshot of the console and the error in it.

使用像这样的API的新手,假设我们只是遗漏了一些明显的东西?

提前感谢您的帮助。

The website with the API info is here

这是我到目前为止的代码,所以你可以自己尝试一下:

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(function() {
        var params = {
            // Request parameters
        };
      
        $.ajax({
            url: "https://emi.azure-api.net/ICPConnectionData/single/?id=0000212621UNA89&" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","f9d45d33880f4e0dac46255d9bc90fce");
            },
            type: "GET",
dataType: 'jsonp',

            // Request body
            data: "{body}",
success:function(data){alert(data)}
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

我认为这是一个跨域问题CORS

更新

尝试添加dataType和成功选项:

$ajax({
  url:'http://yoururl.com',
  method:'GET',
  dataType: 'jsonp',
  success:function(data){alert(data)}
})

更新: 我通过postman测试api url,api很适合在响应中没有Allow-Control-Allow-Origin:*标头使用。导致CORS问题。

当我在jquery ajax中发送请求时,它返回401访问被拒绝错误,这意味着无法在jsonp ajax调用中发送认证头。 解决这个问题的一种方法是:

  • 转到您的API服务器,设置回复标题Allow-Control-Allow-Origin:*

你可以参考这个问题:

How do you send a custom header in a cross-domain (CORS) XMLHttpRequest?

相关问题