简体   繁体   中英

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

I am currently working on a project which get the images(scandir by php) from the server( http://SERVER_IP_ADDRESS/snap/ ) and then pass it to Microsoft Emotion API for emotion analysis.

However, after I pass the concatenated url to the ajax request, I got below error:

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

My code is like this:

<!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>

I tried to remove "JSON_FORCE_OBJECT" in json_encode while the same error shown.

Answered by ADyson : use data: JSON.stringify({"url": info});

Original answer:

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

Thank you ADyson for your help!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM