将 php 数组元素与 url 连接起来,然后传递给 ajax API 请求

Concatenate php array elements with url and then pass to ajax API request

我目前正在做一个项目,从服务器(http://SERVER_IP_ADDRESS/snap/)获取图像(scandir by 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",但出现了同样的错误。

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

原回答:

Based on that, try data: JSON.stringify({"url": info}); . In other words, you send a string which looks like JSON, but produce that string dynamically from an object which contains your URL, not a static value. Also, we don't know what images[221] in your code contains, so we don't know if your final URL value makes sense. – ADyson

谢谢ADyson的帮助!!!