2012-04-13 63 views
-1

即时通讯使用以下从php中检索字符串,我想知道如何使我的字符串成为一个数组。把.get json字符串变成数组?

jQuery的

$.get("get.php", function(data){ 
    alert(data); 
    //alert($.parseJSON(data)); 
}, "json"); 

注释掉部分似乎没有任何效果,所以我真的不能告诉我在做什么错了,可能有人请指教?

如果需要,我可以发布PHP。

谢谢。

PHP

<?php 

$username="root"; 
$password="root"; 
$database="testing"; 

mysql_connect(localhost,$username,$password); 
@mysql_select_db($database) or die("Unable to select database"); 

$name= $_GET['name']; 

$query="SELECT * FROM tableone "; 
$result=mysql_query($query); 

$num=mysql_numrows($result); 

mysql_close(); 

$array = array(); 

$i=0; 
while ($i < $num) { 

    $first=mysql_result($result,$i,"firstname"); 
    $last=mysql_result($result,$i,"lastname"); 
    $date=mysql_result($result,$i,"date"); 
    $ID=mysql_result($result,$i,"id"); 

    $array[$i] = $first; 

    $i++; 
} 

echo json_encode($array); 

?> 

输出:

["James","Lydia","John"]

+0

返回什么数据? – j08691 2012-04-13 15:42:25

+1

由于您已经提供'json'作为返回dataType'data'已经是您可以使用的对象,您不需要'$ .parseJSON(data)'。这假设你的PHP页面以正确的格式返回数据。 – 2012-04-13 15:42:45

+0

请发布生成JSON的PHP代码;你需要改变的是PHP代码,而不是JavaScript - 数据是PHP代码返回的JSON。 – ThiefMaster 2012-04-13 15:42:55

回答

0

你得到JSON出该回调了。它看起来并不像它,因为当你“警告”它被转换成一个由逗号分隔的数组元素列表组成的字符串。

你可以通过做alert(data instanceof Array);看到这将吐出“真”。

+0

好的,以及我给了一个数组,我怎么能'数据'是一个数组? – 2012-04-13 15:53:59

0

你已经找回了比数组更有用的东西。比方说,你的php做到这一点:

<?php echo json_encode(array('John', 'Mary', 'Joseph')); ?> 

里面的功能,你就可以警告数据,你可以访问这样的元素:如果需要通过任何的环

alert(console.log(data[0])); //will alert "John" 
alert(console.log(data[1])); //will alert "Mary" 

元素,你可以这样做:

$(data).each(function(index) { 
    console.log(this.toString()); 
});​ 
+0

多数民众赞成在事情虽然,'alert(console.log(data [0]););'只返回一个字符,而不是全名 – 2012-04-13 16:25:02

+0

也许你忘记了json编码内的数组() – mitchkramez 2012-05-25 18:47:22