拿.get json字符串,变成数组?

时间:2012-04-13 15:40:39

标签: jquery json

我使用以下方法从php中检索字符串,我想知道如何将我的字符串变成数组。

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"]

2 个答案:

答案 0 :(得分:0)

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

你可以通过alert(data instanceof Array);来看到这个,这会吐出“真实”。

答案 1 :(得分: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());
});​
相关问题