与URL相连的PHP数组元素,然后传递到AJAX API请求



我目前正在从服务器(http://server_ip_ip_address/snap/(获取图像(php(的项目(scandir(分析。

但是,当我将串联的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});

原始答案:

基于此,尝试数据:json.stringify({" url":info}(;。换句话说,您发送了一个看起来像JSON的字符串,但是从包含您的URL而不是静态值的对象中动态产生该字符串。另外,我们不知道代码中包含哪些图像[221],因此我们不知道您的最终URL值是否有意义。 - Adyson

谢谢Adyson的帮助!

最新更新