通过AJAX将数组从php传递到javascript [英] Passing array through AJAX from php to javascript

查看:135
本文介绍了通过AJAX将数组从php传递到javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从脚本php生成一个数组。我对数据库中的每个用户都有纬度和经度。
我使用此代码(file.php)获取数据库中的值:

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database. I take the values from the db with this code (file.php):

$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
    $array[]=$data['Latitude'];
    $array[]=$data['Longitude'];
}

echo $array;

我用ajax用这段代码打电话:

and I call with ajax with this code:

$.post('./file.php',
     function( result ){    
         alert(result);
     });

但即使在脚本php中数组是正确的(如果我回显数组[25]我获得在Javascript中我得到了Undefined。
如何以正确的方式获取数组?
谢谢!

but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined". How can I get the array in correct way?? thanks!

编辑:用json_encode编码后($ array);在PHP和JSON.parse(结果)在JavaScript中似乎无法正常工作。
在控制台中我有数组,但我无法访问其值。 (Array [0]给了我undefined)。

edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working. In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").

推荐答案

使用这个

echo json_encode($array);

var arr=JSON.parse(result);

这篇关于通过AJAX将数组从php传递到javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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