【问题标题】:Concatenate php array elements with url and then pass to ajax API request将 php 数组元素与 url 连接,然后传递给 ajax API 请求
【发布时间】:2018-02-19 12:07:03
【问题描述】:

我目前正在从事一个项目,该项目从服务器(http://SERVER_IP_ADDRESS/snap/)获取图像(通过 php 进行扫描),然后将其传递给 Microsoft Emotion API 进行情感分析。

但是,在我将连接的 url 传递给 ajax 请求后,出现以下错误:

Error: {"readyState":4,"responseText":"{\"error\":
{\"code\":\"BadBody\",\"message\":\"JSON parsing error.\"}}","status":400,"statusText":"Bad Request"}

我的代码是这样的:

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

<h2>Face Rectangle</h2>
<ul id="faceRectangle">
<!-- Will populate list with response content -->
</ul>

<h2>Emotions</h2>
<ul id="scores">
<!-- Will populate list with response content -->
</ul>

<body>

<script type="text/javascript">

<?php
    $dir    = "snap";
    $files2 = scandir($dir, 1); 
?>
    var images = <?php echo json_encode(array_slice($files2, 2), JSON_FORCE_OBJECT); ?>;
//Say I want to get image no.221
    var info = "http://SERVER_IP_ADDRESS/snap/" + images[221]; 

    $(function() {
        // No query string parameters for this API call.
        var params = { };

        $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers, also supports "application/octet-stream"
                xhrObj.setRequestHeader("Content-Type","application/json");

                // NOTE: Replace the "Ocp-Apim-Subscription-Key" value with a valid subscription key.
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","YOUR_KEY");
            },
            type: "POST",
            // Request body
            data: '{"url": info}',
        }).done(function(data) {
            // Get face rectangle dimensions
            var faceRectangle = data[0].faceRectangle;
            var faceRectangleList = $('#faceRectangle');

            // Append to DOM
            for (var prop in faceRectangle) {
                faceRectangleList.append("<li> " + prop + ": " + faceRectangle[prop] + "</li>");
            }

            // Get emotion confidence scores
            var scores = data[0].scores;
            var scoresList = $('#scores');

            // Append to DOM
            for(var prop in scores) {
                scoresList.append("<li> " + prop + ": " + scores[prop] + "</li>")
            }
        }).fail(function(err) {
            alert("Error: " + JSON.stringify(err));
        });
    });
    //Show the variables
    document.write(images[221]);
    document.write(info);
</script>
</body>
</html>

我尝试删除 json_encode 中的“JSON_FORCE_OBJECT”,但显示相同的错误。

【问题讨论】:

  • {"url": info} 这是无效的 json
  • @Alexey 抱歉,我是这方面的新手。但我不能做“信息”对吗?关于将网址添加到data: '{"url": info}' 的任何想法?我也失败了data: '{"url":"http://SERVER_IP_ADDRESS/snap/" + images[221];}'
  • 那是 url 编码的吗?
  • 去掉单引号。现在'{"url": info}' 是一个字符串,而不是一个对象。该文字字符串将被发送到服务器,它不会包含您的“信息”变量的内容。
  • @Progrock 嗯...document.wirte(info); 看起来不错。 @ADyson 发生同样的错误。我从docs.microsoft.com/en-us/azure/cognitive-services/emotion/… 复制了javascript代码

标签: php json ajax api microsoft-cognitive


【解决方案1】:

ADyson回答:使用data: JSON.stringify({"url": info});

原答案:

基于此,试试 data: JSON.stringify({"url": info}); .换句话说,您发送一个看起来像 JSON 的字符串,但从包含您的 URL 的对象动态生成该字符串,而不是静态值。此外,我们不知道您的代码中的 images[221] 包含哪些内容,因此我们不知道您的最终 URL 值是否有意义。 ——阿迪森

感谢ADyson的帮助!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2020-10-02
    • 1970-01-01
    相关资源
    最近更新 更多