通过json将php数组传递给javascript数组变量时获取未定义

时间:2018-01-15 07:18:25

标签: javascript php arrays json

我从文件indexOnLoad.php传递一个字符串数组。在我返回此数组后使用JavaScript中的XMLHttpRequest()获取此信息后,我将变量设为'undefined'

HTML代码为:

    <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="NavBar.css">
    <link rel="stylesheet" href="indexCSS.css">
    <script src="indexJS.js" charset="utf-8"></script>
    <script type="text/javascript">
        var arrayString;
    </script>
    <title>Find your Bus</title>
</head>`enter code here`

<body bgcolor=#81D4FA onkeypress="test();" onload="arrayString = indexOnLoad();console.log('arrayString ');console.log(arrayString);">
    <ul class="NavBar">
        <li class="NavBarList" id="Home">
            <a href="#" style="text-decoration: none; color: white;">
                Home
            </a>
            <div class="NavBarListContent" id="homeContent">
                <a href="#">About</a>
                <a href="#">Developers</a>
                <a href="#">Suggestions Box</a>
            </div>
        </li>
        <div style="float: right;">
            <li class="NavBarList">
                Administrator
            </li>
        </div>
    </ul>
    <div class="filler1">

    </div>
    <div class="SearchBox">
        <input type="text" id="textBoxSearchQuery" placeholder="Search for Anywhere..." list="suggestions"><datalist id="suggestions">
            <option value="Manan">Manan</option>
            <option value="Anant">Anant</option>
        </datalist><img src="search-89.png" name="buttonSearch" value="Search" id="buttonSearch">
    </div>

</body>

</html>

请查看body标签和包含主要问题代码的脚本。 JavaScript文件名为"indexJS.js"

        function indexOnLoad() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var obj = JSON.parse(this.responseText);
            return obj;
        }
    };
    xhttp.open("GET", "indexOnLoad.php", true);
    xhttp.send();
}

PHP文件名为“indexOnLoad.php”:

<?php

$array = array("1","2","3");

$json = json_encode($array);
echo $json;
?>

浏览器中的结果

0 个答案:

没有答案