json_encode返回undefined

Rob*_*tan 5 javascript php jquery json

我的脚本从我的json_encode php返回未定义的值

的index.php

<?php
    $returnThis['user'] = "Robin098";
    $returnThis['id'] = "08465";

    echo json_encode($returnThis);
?>
Run Code Online (Sandbox Code Playgroud)

sample.html

<head>
    <script>
        function clickHere(){
            $.get("index.php", function(data) {
            alert(data.user);
            });
        }

    </script>
</head>
       <body>
       <input type="button" onclick = "clickHere();" value="ClickHere!"/> 
       </body>
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Rob*_*b W 3

如果您希望解析 JSON,请使用jQuery.getJSON方法而不是。.get另外,请确保 jQuery 库已正确加载。

    function clickHere(){
        $.getJSON("index.php", function(data) {
            alert(data.user);
        });
    }
Run Code Online (Sandbox Code Playgroud)

目前,您正在使用$.get(url, function(data){...}). 在这种情况下,data是一个包含服务器响应的字符串:

{"user":"Robin098","id":"80465"}
Run Code Online (Sandbox Code Playgroud)

alert(data)在函数内部使用将显示该字符串。