2011-12-09 148 views
5

我的脚本我json_encode PHP返回undefined值json_encode返回undefined

的index.php

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

    echo json_encode($returnThis); 
?> 

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> 

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

+0

'$ aReturn'变量来自你的PHP脚本?你从'$ returnThis'到'$ aReturn'没有任何解释。 – Jasper

回答

3

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

function clickHere(){ 
     $.getJSON("index.php", function(data) { 
      alert(data.user); 
     }); 
    } 

当前,您正在使用$.get(url, function(data){...})。在这方面,data是包含来自服务器的响应的字符串:

{"user":"Robin098","id":"80465"} 

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

+0

嘿,非常感谢,:) –

1

它看起来像你设置$returnThis,但然后返回$aReturn。你不想要:

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

echo json_encode($returnThis); 
+0

对不起错误输入。 –

+0

@RobinCarloCatacutan - 在这种情况下,它看起来像Rob W的答案就是你想要的。或者.getJSON或$ .ajax的dataType设置为json –

+0

不,我只是输入了错误代码,与我的实际代码不一样。你帮了我。 TNX。 –