首页 > 解决方案 > 从 javascript 发送 HTTP 请求时,如何从 PHP 脚本返回数组?

问题描述

嗨,我是 PHP 新手,我遇到了一个问题,我想向PHP脚本发送 HTTP 请求,它应该返回一个 2x2 数组。但是使用我的代码,我什么也没收到。

index.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "get_info.php");
        xhr.onload = function () {
            console.log(xhr.responseText);                    
        };
        xhr.send();
    </script>    
</body>
</html>

get_info.php:

<?php
    $return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
    return $return_array;
?>

标签: javascriptphp

解决方案


json_encode()该数组,以及echo(不返回!)生成的 json 字符串:

<?php
    $return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
    echo json_encode($return_array);
    // remove the trailing ?> just to make sure you don't send an unwanted newline, space or smth

然后在javascript中

var myArray = JSON.parse(xhr.responseText); 
console.log(myArray);

再次用它制作一个js数组。

一些文档和相关阅读:


推荐阅读