如何向microsoft vision api发送ajax请求?

时间:2016-05-30 15:42:01

标签: javascript ajax microsoft-cognitive

我正在关注文档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
        "returnFaceId": "true",
        "returnFaceLandmarks": "false",
        "returnFaceAttributes": "{age}",
    };

    $.ajax({
        url: "https://api.projectoxford.ai/face/v1.0/detect?" + $.param(params),
        beforeSend: function(xhrObj){
            // Request headers
            xhrObj.setRequestHeader("Content-Type","application/json");
            xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","e2c75ad5d44846d590ac7c2dcc2f210e");
        },
        type: "POST",
        // Request body
        data: "http://newsrescue.com/wp-content/uploads/2015/04/happy-person.jpg",
    })
    .done(function(data) {
        alert("success");
    })
    .fail(function() {
        alert("error");
    });
});
</script>
</body>
</html>

但我一直收到错误代码404资源未找到。谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:3)

使用enter image description here进行快速检查会显示您的参数不正确(不是404)。

一些事情:

  1. returnFaceAttributes应为"age"(不是"{age}"
  2. data需要一个参数名称
  3. 试试这个(查看data更新):

    <html>
    <head>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
        <title>JSSample</title>
    
    </head>
    <body>
    
    <script type="text/javascript">
        $(function() {
        var params = {
            // Request parameters
            "returnFaceId": "true",
            "returnFaceLandmarks": "false",
            "returnFaceAttributes": "age",
        };
    
        $.ajax({
            url: "https://api.projectoxford.ai/face/v1.0/detect?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","e2c75ad5d44846d590ac7c2dcc2f210e");
            },
            type: "POST",
            // Request body
            data: '{ "url": "http://newsrescue.com/wp-content/uploads/2015/04/happy-person.jpg"}'
        })
        .done(function(data) {
            console.log(data);
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
    </script>
    </body>
    </html>
    

    我创建了一个Postman以确保它有效(根据微软,她的年龄为19.3岁)。

    最后一个重要注释。立即更改您的Ocp-Apim-Subscription-Key密钥!