以.get json字符串,变成数组? [英] Taking .get json string, turn into array?

查看:93
本文介绍了以.get json字符串,变成数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下内容从php检索字符串,我想知道如何将我的字符串变成数组.

Im using the following to retrieve a string from php, i would like to know how to make my string into an array.

jQuery

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

注释掉的部分似乎没有任何作用,所以我无法真正说出我在做错什么,有人可以请教吗?

the commented out section seems to have no effect, so I cant really tell what I am doing wrong, could someone please advice?

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

I can post the PHP if needed.

谢谢.

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

推荐答案

您已经找回了比数组有用的东西.假设您的php做到了这一点:

You're already getting back something as useful than an array. Let's say your php does this:

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

在提醒数据的函数中,您可以访问以下元素:

Inside your function where you're alerting the data, you can get access to the elements like this:

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

如果您需要遍历任何元素,可以这样做:

If you need to loop through any of the elements, you can do so like this:

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

这篇关于以.get json字符串,变成数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆