2011-12-09 149 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。 –