通过JSON将PHP数组转换为jquery数组 [英] PHP array to jquery array via JSON

查看:478
本文介绍了通过JSON将PHP数组转换为jquery数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有些困惑,为什么下面的方法不起作用.

Im having a little confusion why the following is not working.

get.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[] = $first;

    $i++;
}

echo json_encode($array);

?>

jQuery

var arr = new Array();

    $.get("get.php", function(data){
         arr = data;
         alert(arr);
    }, "json");

运行以下命令时,我会得到一个看起来像这样的名称列表

When I run the following I get a list of names that looks like this

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

但是,当我尝试单选一个条目(例如arr [2])时,我仅给出一个"J",为什么元素像我期望的那样单个输入一个条目?

But when I try to single out an entry such as arr[2], i am give just a 'J', why is it that the elements arnt single entries like I would expect?

任何人都可以伸出援手吗?

Can anyone lend a hand?

谢谢!

更新

$.get("get.php", function(data){

     arr = $.parseJSON(data);
     alert(arr);
}, "json");

似乎没有返回结果吗?

推荐答案

data包含JSON字符串,因此arr[2]将是字符串中的第三个字符.您需要使用$.parseJSON(data).

data contains a string of the JSON, so arr[2] will be the third character in the string. You need to use $.parseJSON(data).

这篇关于通过JSON将PHP数组转换为jquery数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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